我们说我有一份水果和重量元组对列表。
[('apple', 5), ('banana', 9), ('coconut', 14)...]
我们说我也有一份水果和价格对的清单。
[('apple', 0.99), ('banana', 1.24), ('coconut', 3.20)...]
如何获得水果,重量和价格清单?我们可以假设两个列表都有相同的结果。不需要外部模块的答案的奖励积分。
答案 0 :(得分:2)
weights = [('apple', 5), ('banana', 9), ('coconut', 14)]
prices = [('apple', 0.99), ('banana', 1.24), ('coconut', 3.20)]
您可以使用词典理解
将两个列表转换为词典,将水果作为键weights = {fruit:weight for fruit, weight in weights}
prices = {fruit:price for fruit, price in prices}
此步骤可以简单地用dict
函数编写,就像这样
weights, prices = dict(weights), dict(prices)
然后列表构造很简单,列表理解
print [(fruit, weights[fruit], prices[fruit]) for fruit in weights]
# [('coconut', 14, 3.2), ('apple', 5, 0.99), ('banana', 9, 1.24)]
答案 1 :(得分:0)
你可以这样做(假设它们在此时被相应地排序):
>>> list1 = [('apple', 5), ('banana', 9), ('coconut', 14)]
>>> list2 = [('apple', 0.99), ('banana', 1.24), ('coconut', 3.20)]
>>>
>>> [x+y for x, y in zip(list1, [(t[1],) for t in list2])]
[('apple', 5, 0.99), ('banana', 9, 1.24), ('coconut', 14, 3.2)]
答案 2 :(得分:0)
如果你有:
weights = [('apple', 5), ('banana', 9), ('coconut', 14)]
prices = [('apple', 0.99), ('banana', 1.24), ('coconut', 3.20)]
你可以通过简单的列表理解来实现:
[(fruit, weight, dict(prices)[fruit]) for fruit, weight in weights]
编辑:对于大型列表可能无效。这应该更好:
prices_dict = dict(prices)
[(fruit, weight, prices_dict[fruit]) for fruit, weight in weights]