python 匹配嵌套列表中的索引和元素

lbsnaicq  于 2023-02-07  发布在  Python
关注(0)|答案(4)|浏览(126)

我有一个嵌套列表

elements = [['A', 'B'],['B','C'],['D','E','F']]

我有一个索引列表

ordered elements = ['A','B','C', 'D', 'E', 'F']

index= [308,302,303,405,506,609]

我们知道元素和索引是按顺序匹配的
我想通过索引重新创建嵌套列表,这意味着输出将如下所示:

out = [[308,302],[302,303],[405,506,609]]
mbzjlibv

mbzjlibv1#

您可以使用Map字典:

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}
im9ewurl

im9ewurl2#

  • 准备Map(字母到索引)
  • 遍历元素并赋值给输出(使用嵌套的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)
nle07wnf

nle07wnf3#

我不推荐这样做,但如果你想剪短,也许你可以试试这个:

result = [[index[ordered_elements.index(el_l1)] for el_l1 in el] for el in elements]
mnemlml8

mnemlml84#

虽然此处没有安全检查,但您可以按以下方式操作:

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]]

相关问题