簡體   English   中英

Python - 使用 lambda 過濾元組列表

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

我嘗試使用另一個元組更新元組值。

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

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

預期結果:

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

這樣做的正確方法是什么? ,我嘗試了以下代碼,但沒有成功。 我很樂意提供幫助

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

我會使用字典,似乎更適合您的任務:

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:

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

您應該使用 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 ) )

使factors成為字典:

factors = dict(factors)

然后使用 dict comprehension 使用現有的關聯列表grades構建一個新的dict

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

如果你真的需要一個元組的元組,使用

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

改用計數器怎么樣?

from collections import Counter

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

更新很簡單

grade += factors

或者

grade.update(factors)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM