我如何 append/merge/pair 相同索引或键的值并忽略没有匹配索引或键的值?

How would I append/merge/pair values of the same index or key and ignore values that don't have a matching index or key?

我正在尝试 pair/merge 将同一索引或键值对的两个列表中的值列在一起。如果该值没有密钥,则不应配对,如果它有密钥,则应该配对。

我尝试使用它们的索引附加值,但是,它 returns 一个 IndexError:列表索引超出范围。我已经使用它们的密钥将它们配对,但输出不是我想要的输出

list1 = [[0, 1], [1, 2], [3, 1]]
list2 = ["append", "values", "to", "one", "another"]

#my attempt at pairing the lists together 
merger = dict(zip(list1, list2))
print(merger)

#converted the first value of the values in list 1 to a key
getKey = {words[0]:words[1:] for words in list1}

#OrderedDict() method to append the two lists
newDict = OrderedDict()
for i, v in enumerate(list2): 
    newDict.setdefault(v, []).append(getKey[i])
print(newDict)

产出

>>> merger output: 
{'append': [0, 1], 'values': [1, 2], 'to':[3, 1]}

>>> expected merger output: 
{'append': [0, 1], 'values':[1, 2], 'one':[3, 1]}

>>> newDict output: 
    IndexError: list index out of range

>>> newDict expected output:
    OrderDict([('append', [[0,1]]), ('values', [[1,2]]), ('one', [[3,1]])]

我在这里想要实现的是,当且仅当它与键匹配时,list1 才附加到 list2,否则它不应该输出任何内容。

我不知道如何解决这个问题。提前致谢

如果我理解正确的话你可以这样做:

list1 = [[0, 1], [1, 2], [3, 1]]
list2 = ["append", "values", "to", "one", "another"]

# create lookup tables (index, values)
lookup1 = {k : [k, v] for k, v in list1}
lookup2 = {i : v for i, v in enumerate(list2)}

merge = {lookup2[k] : v  for k, v in lookup1.items()}

print(merge)

输出

{'append': [0, 1], 'one': [3, 1], 'values': [1, 2]}

请注意,此解决方案假定 list1 中子列表的第一个值对应于索引。