英文:
match indexes and elements in a nested list
问题
out = [[308, 302], [302, 303], [405, 506, 609]]
英文:
I have a nested list
elements = [['A', 'B'],['B','C'],['D','E','F']]
and I have list of indexes
ordered elements = ['A','B','C', 'D', 'E', 'F']
index= [308,302,303,405,506,609]
we know the elements and the indexes are matching by order
I want to recreate nested list by the indexes meaning the output would look like this:
out = [[308,302],[302,303],[405,506,609]]
答案1
得分: 1
你可以使用一个映射字典:
dmap = dict(zip(ordered_elements, index))
out = [[dmap[key] for key in lst] for lst in elements]
输出:
>>> out
[[308, 302], [302, 303], [405, 506, 609]]
>>> dmap
{'A': 308, 'B': 302, 'C': 303, 'D': 405, 'E': 506, 'F': 609}
英文:
You can use a mapping dict:
dmap = dict(zip(ordered_elements, index))
out = [[dmap[key] for key in lst] for lst in elements]
Output:
>>> out
[[308, 302], [302, 303], [405, 506, 609]]
>>> dmap
{'A': 308, 'B': 302, 'C': 303, 'D': 405, 'E': 506, 'F': 609}
答案2
得分: 0
- 准备映射(字母到索引)
- 遍历元素并分配给输出(使用嵌套的for/list理解)
例如:
ordered_elements = ['A', 'B', 'C', 'D', 'E', 'F']
index = [308, 302, 303, 405, 506, 609]
element_index_mapping = {letter: idx for e, letter in zip(ordered_elements, index)}
out = []
for letters in elements:
indices_for_letters = []
for letter in letters:
indices_for_letters.append(element_index_mapping.get(letter))
out.append(indices_for_letters)
英文:
- prepare mapping (letter to index)
- iterate over the elements and assign to output (using nested for/list comprehension)
e.g.
ordered_elements = ['A','B','C', 'D', 'E', 'F']
index= [308,302,303,405,506,609]
element_index_mapping = {letter:idx for e, letter in zip(ordered_elements, index)}
out = []
for letters in elements:
indices_for_letters = []
for letter in letters:
indices_for_letters.append(element_index_mapping.get(letter))
out.append(indices_for_letters)
答案3
得分: 0
你可以这样做,尽管这里没有进行安全检查:
elements = [['A', 'B'], ['B', 'C'], ['D', 'E', 'F']]
ordered_elements = ['A', 'B', 'C', 'D', 'E', 'F']
index = [308, 302, 303, 405, 506, 609]
out = [[index[ordered_elements.index(c)] for c in sl] for sl in elements]
print(out)
输出:
[[308, 302], [302, 303], [405, 506, 609]]
英文:
You could do it like this although there are no safety checks here:
elements = [['A', 'B'], ['B', 'C'], ['D', 'E', 'F']]
ordered_elements = ['A', 'B', 'C', 'D', 'E', 'F']
index = [308, 302, 303, 405, 506, 609]
out = [[index[ordered_elements.index(c)] for c in sl] for sl in elements]
print(out)
Output:
[[308, 302], [302, 303], [405, 506, 609]]
答案4
得分: 0
我不建议这样做,但如果你想要简化的话,也许你可以尝试这样做:
result = [[index[ordered_elements.index(el_l1)] for el_l1 in el] for el in elements]
英文:
I don't recommend this, but if you want it short, maybe you could try this:
result = [[index[ordered_elements.index(el_l1)] for el_l1 in el] for el in elements]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论