1

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 ?

8
  • 1
    In the second code, the fact that you used sum as variable name caused your error. I replaced the others list/sum but left this one for reproducibility of the error Commented Jul 11, 2022 at 4:26
  • 1
    Also, I'm not sure what you want to do with the output, but print should really never be used for its property to yield elements. Use a generator, or collect in a list. Commented Jul 11, 2022 at 4:28
  • 1
    I don't use this names in my code, it was for the example, I didn't know it was so important... thank you ! Commented Jul 11, 2022 at 4:29
  • btw, I will not use prints, I only need to know the sum of each lists to sort them afterwards. thanks for the advices Commented Jul 11, 2022 at 4:38
  • 1
    Then you don't even need to sort, just filter: [x for x in lst if sum(list(zip(*x))[1])<=500] Commented Jul 11, 2022 at 5:02

7 Answers 7

2

Check this out.

result = [("".join(list(zip(*tup))[0]), sum(list(zip(*tup))[1])) for tup in lst]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

1

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

Comments

1

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

Comments

1

Try this:

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.