简体   繁体   English

如何在python中对N个列表的元素求和?

[英]How to sum elements of N lists in python?

I have a list of tuples of lists... :我有一个列表元组的列表...:

lst = [(['a', 1], ['b', 2]), (['c', 3], ['d', 4], ['e', 5])]

And I want to get the sum of index[1] of every lists in each tuples (first tuple = 3, second tuple = 12) result can look like this:我想得到每个元组中每个列表的 index[1] 的总和(第一个元组 = 3,第二个元组 = 12)结果可能如下所示:

['ab', 3]
['cde', 12]

I tried this :我试过这个:

for tuples in lst:
    total = [x + y for (x, y) in zip(*tuples)]
    print(total)

but if a tuple has more than 2 values (like the second one) I will get a value error.但是如果一个元组有两个以上的值(比如第二个),我会得到一个值错误。

I need to get the sum of every lists no matter the number of lists in each tuples无论每个元组中的列表数量如何,我都需要获取每个列表的总和

So I tried this instead:所以我尝试了这个:

for tuples in lst:
    sum = [sum(x) for x in zip(*tuples)]

But I get a TypeError: 'list' object is not callable但我得到一个TypeError: 'list' object is not callable

Any ideas ?有任何想法吗 ?

Simply this:简单地说:

L = [(['a', 1], ['b', 2]), (['c', 3], ['d', 4], ['e', 5])]

for t in L:
    s = ''.join(x[0] for x in t)
    S = sum(x[1] for x in t)
    print([s, S])

and refrain to define variable names using python keywords...并避免使用 python 关键字定义变量名......

I hope this helps我希望这有帮助

lst = [ (['a', 1], 
         ['b', 2]), 
         
        (['c', 3], 
         ['d', 4], 
         ['e', 5]) ]

for i in list:
  print["".join([d for d in zip(*i)][0]), sum([d for d in zip(*i)][1])]

The problem with the first code was;第一个代码的问题是; You had x+y , it will only work for the first iteration of the loop, cause there are only 2 values to unpack.你有x+y ,它只适用于循环的第一次迭代,因为只有 2 个值需要解包。 but it won't work for the second iteration.但它不适用于第二次迭代。

And the problem with the second code you had was, that you were trying to add a type int and type str together第二个代码的问题是,您试图将类型int和类型str一起添加

  • Just to avoid the confusion, I'm renaming the variable list to lst只是为了避免混淆,我将变量list重命名为lst

Here is an idea, use a nested list comprehension with zip and a custom function to sum or join:这是一个想法,使用带有zip的嵌套列表理解和自定义函数来求和或加入:

lst = [(['a', 1], ['b', 2]), (['c', 3], ['d', 4], ['e', 5])]

def sum_or_join(l):
    try:
        return sum(l)
    except TypeError:
        return ''.join(l)
    
out = [[sum_or_join(x) for x in zip(*t)] for t in lst]

Or if you really have always two items in the inner tuples, and always ('string', int) :或者,如果您确实在内部元组中总是有两个项目,并且总是('string', int)

out = [[f(x) for f, x in zip((''.join, sum), zip(*t))]
       for t in lst]

Output: [['ab', 3], ['cde', 12]]输出: [['ab', 3], ['cde', 12]]

This should be clear and straightforward.这应该是明确和直接的。

A = [(['a', 1], ['b', 2]), (['c', 3], ['d', 4], ['e', 5])]

result = []
for tup in A:
    char, value = "", 0
    for x, y in tup:
        char += x
        value += y
    result.append([char, value])
print(result)

Using zip :使用zip

result = []
for tup in A:
    tmp = []
    for x in zip(*tup):
        if type(x[0]) == str:
            tmp.append(''.join(x))
        elif type(x[0]) == int:
            tmp.append(sum(x))
    result.append(tmp)
print(result)

Sample O/P:样品 O/P:

[['ab', 3], ['cde', 12]]

Following one-liner produces desired [('ab', 3), ('cde', 12)] in result以下单行产生所需[('ab', 3), ('cde', 12)]结果

lst = [(['a', 1], ['b', 2]), (['c', 3], ['d', 4], ['e', 5])] # don't use list 
                                                             # as variable name
# One-liner using builtin functions sum, list and Walrus operator
result = [(''.join(p[0]), sum(p[1])) for sublist in lst if (p:=list(zip(*sublist)))]

Note following should not be used as variable names since conflict with popular builtin functions:注意以下不应用作变量名,因为与流行的内置函数冲突:

  • sum
  • list列表

尝试这个:

result = [[''.join([x for x,y in item]),sum([y for x,y in item])] for item in lst]

看一下这个。

result = [("".join(list(zip(*tup))[0]), sum(list(zip(*tup))[1])) for tup in lst]

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

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