-1

I have a list 'L'

L = [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]

I want this list to

[ 3, 4, 5, 6, 5, 6, 7, 7, 8, 9]

which is sum of element. What is appropriate code? I want shortest code Use map method?

3 Answers 3

0

Seems like homework, but OK.

We need to transform the strings inside the tuples into ints, and then sum them, there are a trillion ways of doing this. This is a general solution so it works even if the tuples in the original list have variable lengths.

First using map as you want

list(map(lambda tup: sum(map(int,tup)), L))

The list call is just used to create a list from the map object.

You can also use list comprehensions

[sum(int(x) for x in tup) for tup in L]

You can also mix and match the map in the comprehension call like this to get the shortest code.

[sum(map(int,tup)) for tup in L]
1
  • thank you! It is not homework. This problem is part of my algorithm problem. The answer said runtime error, so I need to write code more shorter. This code is work. Thank you. Maybe I need to study map method more
    – Gamrom
    Commented Jun 8, 2020 at 1:46
0

Here you go. :)

casting = [  (int(i), int(j)) for i,j in L ] 
sumVariable = [ sum(i) for i in casting ]
0

you can try this :

alpha = [int(x[0])+int(x[1]) for x in L]

Not the answer you're looking for? Browse other questions tagged or ask your own question.