我有一个像这样的元组列表
[(300.0, 'g', 'peanuts'),
(0.5, 'tsp', 'salt'),
(2.0, 'tsp', 'oil'),
(300.0, 'g', 'peanuts'),
(1.0, 'tsp', 'salt'),
(3.0, 'tsp', 'oil')]
同名我要加数量
[(600.0, 'g', 'peanuts'),
(1.5, 'tsp', 'salt'),
(5.0, 'tsp', 'oil')]
我尝试使用 for...in 循环从列表中获取项目,但没有进一步步骤的线索。
您可以在遍历元组列表时使用字典来跟踪每种成分的数量。
然后将字典转换回元组列表,其中包含每种成分的总量。
ingredients = [(300.0, 'g', 'peanuts'), (0.5, 'tsp', 'salt'), (2.0, 'tsp', 'oil'), (1.0, 'cup', 'mung'), (0.5, 'tsp', 'salt'), (0.75, 'tsp', 'pink'), (0.25, 'tsp', 'garlic'), (0.25, 'tsp', 'onion'), (0.125, 'tsp', 'pepper'), (0.25, 'tsp', 'turmeric'), (1.0, 'tsp', 'oil'), (1.0, 'cup', 'soy')]
ingredient_dict = {}
for quantity, unit, name in ingredients:
if name in ingredient_dict:
ingredient_dict[name][0] += quantity
else:
ingredient_dict[name] = [quantity, unit]
result = [(ingredient_dict[name][0], ingredient_dict[name][1], name) for name in ingredient_dict]
print(result)
输出:
[(300.0, 'g', 'peanuts'), (1.0, 'tsp', 'salt'), (3.0, 'tsp', 'oil'), (1.0, 'cup', 'mung'), (0.75, 'tsp', 'pink'), (0.25, 'tsp', 'garlic'), (0.25, 'tsp', 'onion'), (0.125, 'tsp', 'pepper'), (0.25, 'tsp', 'turmeric'), (1.0, 'cup', 'soy')]
您可以使用
defaultdict
来跟踪每个名称的总数。
from collections import defaultdict
l = [(300.0, 'g', 'peanuts'), (0.5, 'tsp', 'salt'), (2.0, 'tsp', 'oil'), (1.0, 'cup', 'mung'), (0.5, 'tsp', 'salt'), (0.75, 'tsp', 'pink'), (0.25, 'tsp', 'garlic'), (0.25, 'tsp', 'onion'), (0.125, 'tsp', 'pepper'), (0.25, 'tsp', 'turmeric'), (1.0, 'tsp', 'oil'), (1.0, 'cup', 'soy')]
d = defaultdict(int)
for v, *k in l: d[tuple(k)] += v
res = [(v, *k) for k, v in d.items()]
print(res)
您想“提取一个对象”来总结一个对象列表。
这就是“reduce”功能的用途:
from functools import reduce
my_tuples = [(300.0, 'g', 'peanuts'), (0.5, 'tsp', 'salt'), (2.0, 'tsp', 'oil'), (1.0, 'cup', 'mung'), (0.5, 'tsp', 'salt'), (0.75, 'tsp', 'pink'), (0.25, 'tsp', 'garlic'), (0.25, 'tsp', 'onion'), (0.125, 'tsp', 'pepper'), (0.25, 'tsp', 'turmeric'), (1.0, 'tsp', 'oil'), (1.0, 'cup', 'soy')]
def sum_stuff(current_sum_dict, peanut_tuple):
if peanut_tuple[2] in current_sum_dict.keys():
current_sum_dict[peanut_tuple[2]] += peanut_tuple[0]
else:
current_sum_dict[peanut_tuple[2]] = peanut_tuple[0]
return current_sum_dict
print(reduce(sum_stuff, my_tuples, {}))
reduces 接受两个参数(加上一个可选的初始值设定项)。
第二个参数是您在我称之为代码示例中的列表
my_tuples
.
第一个是带有两个参数的“函数”:
reduce
函数在整个列表上循环并在每次迭代时更新“减少”值。
reduce 是官方和本地
functools
包的一部分,您无需安装任何额外的包即可使用它。
你经常看到人们使用 lambda 表达式而不是定义一个实际的函数,尤其是当函数很短的时候:
在这个例子中,我使用 lambda 表达式来计算“花生”
reduce(lambda a, b: a + b[0] if b[2] == 'peanuts' else a, my_tuples, 0)