简体   繁体   English

在Python中汇总列表 - 在元组和另一个列表中

[英]Summing a list in Python - within a tuple and another list

Not sure if it's a dup - will delete if so, just haven't found one for this specific scenario. 不确定它是否是重复 - 如果是这样将删除,只是没有为此特定方案找到一个。 I have a complex list full of tuples, which contain strings and lists. 我有一个包含字符串和列表的复杂列表,其中包含元组。

I need to replace the deepest lists with int values, which are the sum of those lists. 我需要用int值替换最深的列表,这些值是这些列表的总和。 I've tried half a dozen loop combinations to tackle it - nothing seems to work. 我已经尝试了六个循环组合来解决它 - 似乎没有任何效果。

[('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]

Needs to become: 需要成为:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

So that I can return the new list combo sorted by the values of the summed lists. 这样我就可以返回按汇总列表的值排序的新列表组合。

You can make a concise, readable comprehension with something like: 您可以使用以下内容进行简明易懂的理解:

[(abbr, sum(t)) for abbr, t in l]

result: 结果:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

Using map 使用map

Ex: 例如:

lst = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]
print(list(map(lambda x: (x[0], sum(x[1])), lst)))

or list comprehension list comprehension

Ex: 例如:

print([(i[0], sum(i[1])) for i in lst])

Output: 输出:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]
oldlst = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]

newlst = list([(i[0], sum(i[1])) for i in oldlst])

Check here . 点击这里

Let's use list comprehensions to solve it - 让我们使用列表推导来解决它 -

myList = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]
myList_out = [(i[0],sum(i[1])) for i in myList]
myList_out
    [('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

By using collections.defaultdict. 通过使用collections.defaultdict。 :

from collections import defaultdict
xList = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]
testDict = defaultdict(int)
for key, val in xList:           
        testDict[key] = val[0] + val[1]

print(testDict.items())

OUTPUT: OUTPUT: 出

lst = [('MED', [1, 1]),('COP', [3, 1]),('GRO', [1, 5]),('RRE', [5, 3]),('PRO', [4, 6])]

print [(text, sum(num)) for text, num in lst]

result: 结果:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

Try this: 尝试这个:

l1 = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]

mod_l1 = [(abbr, sum(t)) for abbr, t in l1]

required_l1 = sorted(mod_l1, key=lambda order: order[1])

result: 结果:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

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

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