2024-04-29 12:01:33 发布
网友
假设我有一个水果和重量元组对的列表。你知道吗
[('apple', 5), ('banana', 9), ('coconut', 14)...]
假设我还有一份水果和价格对的清单。你知道吗
[('apple', 0.99), ('banana', 1.24), ('coconut', 3.20)...]
我怎样才能得到一份水果、重量和价格的清单?我们可以假设两个列表都有相同的结果。不需要外部模块的答案的加分。你知道吗
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函数编写,如下所示
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)]
如果您有:
你可以通过简单的列表理解:
[(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)]
您可以使用字典理解将这两个列表转换为字典,以水果作为键
这个步骤可以简单地用
dict
函数编写,如下所示然后列表的构造是琐碎的,需要列表理解
如果您有:
你可以通过简单的列表理解:
编辑:对于大型列表可能无效。这应该更好:
您可以这样做(假设此时相应地订购):
相关问题 更多 >
编程相关推荐