我有以下列表:
mylist = [('word1', '10', 200), ('word2', '10', 450), ('word1', '136', 300), ('word2', '110', 666)]
我想知道如何获得输出:
[('10', 650), ('136',300), ('110', 666)]
所以将位置[1]和[2]添加到新列表或词典中。但是如果word1
和word2
具有相同的[1],则将[1]与[2]的总和相加到新列表或词典中。
我希望我足够清楚,否则请求离开。
答案 0 :(得分:1)
请将您的list
列表重命名为list_
(或其他内容),以便不会覆盖对内置列表的引用。
alrd_seen={}
for l in list_:
alrd_seen[l[1]] = alrd_seen.get(l[1], 0) + l[2]
print list(alrd_seen.items())
with defaultdict;
from collections import defaultdict as dd
alrd_seen = dd(0)
for l in list_:
alrd_seen[l[1]] += l[2]
print list(alrd_seen.items())
答案 1 :(得分:0)
首先将变量名称从list
更改为其他内容,例如lst
,因为list
混淆了数据类型。
尝试类似:
getfunc = lambda x, lst: sum(i[2] for i in lst if i[1] == x)
dct = { y: getfunc(y, lst) for x, y, z in lst}
print (dct)
给出输出:
{'110': 666, '10': 650, '136': 300}
答案 2 :(得分:0)
mylist = [('word1', '10', 200), ('word2', '10', 450), ('word1', '136', 300), ('word2', '110', 666)]
# Since you need to refer back to previous values while processing,
# we'll use a dictionary as intermediate storage
nl = {}
# Use unpacking to make code more readable and avoid the use of
# error-prone index-based referencing
for _, key, value in mylist:
# Use dict.get(key, default_value_if_missing) to retrieve the
# current value or 0 if it is a newly seen key. Add the current
# value and store.
nl[key] = nl.get(key, 0) + value
# dict.items() returns a "set-like" list of key-value pairs.
# Convert it to a regular list to get a list of tuples.
list(nl.items())
# [('136', 300), ('10', 650), ('110', 666)]