Rlyeh
Rlyeh

Reputation: 25

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:

['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

Any ideas ?

Upvotes: 1

Views: 130

Answers (7)

Capt.Pyrite
Capt.Pyrite

Reputation: 911

I hope this helps

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

for i in lst:
  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. 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

  • Just to avoid the confusion, I'm renaming the variable list to lst

Upvotes: 1

Deepeshkumar
Deepeshkumar

Reputation: 443

Check this out.

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

Upvotes: 2

hamidreza samsami
hamidreza samsami

Reputation: 419

Try this:

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

Upvotes: 1

Hariharan Ragothaman
Hariharan Ragothaman

Reputation: 582

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:

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:

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

Upvotes: 1

DarrylG
DarrylG

Reputation: 17156

Following one-liner produces desired [('ab', 3), ('cde', 12)] in result

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

Upvotes: 1

mozway
mozway

Reputation: 260300

Here is an idea, use a nested list comprehension with zip and a custom function to sum or join:

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

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

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

Upvotes: 1

Julien
Julien

Reputation: 15071

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

Upvotes: 1

Related Questions