简体   繁体   English

Python - 使用 lambda 过滤元组列表

[英]Python - Filtering a list of tuples with lambda

I try to update tuple values using another tuple.我尝试使用另一个元组更新元组值。

grade = (('a', 10), ('b', 20), ('c', 30), ('d', 40))

factors = (('a', 1), ('b', 2))

Expected result:预期结果:

result  = (('a', 11), ('b', 22), ('c', 30), ('d', 40))

What would be the right way to do this?这样做的正确方法是什么? , I tried the following code but it did not work. ,我尝试了以下代码,但没有成功。 I would be happy to help我很乐意提供帮助

print(list(filter(lambda list_a: list(map(lambda x, y: x+ y, list_a[0], grade[1])) not in list(map(lambda x: x[0], factors)), grade)))

I'd use dictionaries, seem more suited for your task:我会使用字典,似乎更适合您的任务:

factors = dict(factors)
grade = dict(grade)
{k: grade[k] + factors[k] if k in factors.keys() else grade[k] for k  in grade.keys()}

Output: Output:

{'a': 11, 'b': 22, 'c': 30, 'd': 40}

You should use a dict, and you can take advantage of its get method to get 0 for non existing keys:您应该使用 dict,并且可以利用它的get方法为不存在的键获取 0:

grade = (('a', 10), ('b', 20), ('c', 30), ('d', 40))

factors = (('a', 1), ('b', 2))
factors = dict(factors)

new_grades = [(g[0], g[1] + factors.get(g[0], 0)) for g in grade]
print(new_grades)
# [('a', 11), ('b', 22), ('c', 30), ('d', 40)]
fact = dict(factors) result = list( map( lambda x: (x[0], x[1] + fact.get(x[0], 0)), grade ) )

Make factors a dict:使factors成为字典:

factors = dict(factors)

then use a dict comprehension to build a new dict using the existing association list grades :然后使用 dict comprehension 使用现有的关联列表grades构建一个新的dict

result = {g: score + factors.get(g, 0) for g, score in grade}

If you really need a tuple of tuples, use如果你真的需要一个元组的元组,使用

result = tuple((g, score + factors.get(g,0)) for g, score in grade)

How about using Counters instead?改用计数器怎么样?

from collections import Counter

grade = Counter(dict(grade))
factors = Counter(dict(factors))

The the update is simply更新很简单

grade += factors

or或者

grade.update(factors)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM