从两个二维列表中创建一个三维列表,每个二维列表中有一个公共元素

2024-04-29 12:01:33 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个水果和重量元组对的列表。你知道吗

[('apple', 5), ('banana', 9), ('coconut', 14)...]

假设我还有一份水果和价格对的清单。你知道吗

[('apple', 0.99), ('banana', 1.24), ('coconut', 3.20)...]

我怎样才能得到一份水果、重量和价格的清单?我们可以假设两个列表都有相同的结果。不需要外部模块的答案的加分。你知道吗


Tags: 模块答案apple列表价格banana元组重量
3条回答
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)]

如果您有:

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]

您可以这样做(假设此时相应地订购):

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

相关问题 更多 >