【发布时间】:2019-05-28 04:37:02
【问题描述】:
我正在尝试将来自同一索引或键值对的两个列表中的列表值配对/合并在一起。如果该值没有键,则不应配对,如果确实有键,则应配对。
我尝试使用它们的索引附加值,但是,它返回一个 IndexError: list index out of range。我已经使用他们的密钥将它们配对,但输出不是我想要的输出
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 ,否则它不应该输出任何东西。
我不确定如何解决这个问题。提前致谢
【问题讨论】:
-
1.我建议阅读有关不同功能的 Python 文档(例如 docs.python.org/3.3/library/functions.html#zip),它将解释为什么您没有得到预期的输出。列表迭代也是如此。 2.考虑把你的问题写得更清楚,你问的不是很清楚
-
显然
'to'不是预期输出中的关键。目前尚不清楚为什么不这样做。这可能与以“...当且仅当 it 匹配键”结尾的规则有关。但不清楚这句话中的“它”指的是什么。
标签: python list indexing ordereddictionary