Ash3060
Ash3060

Reputation: 340

Operation on list in list of list using list comprehension

I am trying to print a list of tuples containing the size of each list from list of list

ex:

l=[1,3,4,5,6,7],[1,1],[1,9,9]

print(list(map(lambda x: ("sum",sum(1 for i in l)),l))) 

Upvotes: 0

Views: 65

Answers (4)

555Russich
555Russich

Reputation: 404

That's what you want

l=[1,3,4,5,6,7],[1,1],[1,9,9]
print([('sum', len(l_)) for l_ in l])

Output:

[('sum', 6), ('sum', 2), ('sum', 3)]

But i think that is not sum, it's len, so:

l=[1,3,4,5,6,7],[1,1],[1,9,9]
print([('len', len(l_)) for l_ in l])

Output:

[('len', 6), ('len', 2), ('len', 3)]

Upvotes: 0

timgeb
timgeb

Reputation: 78680

You have a bug, it should be

sum(1 for i in x) # x, not l

Also, len(x) would give you the same number.

The list-comprehension solution is

[('sum', len(x)) for x in l]

Upvotes: 2

Bob
Bob

Reputation: 14654

I guess what you want is

print(list(map(lambda x: ("sum",sum(1 for i in x)),l))) 

The the mapping function has an agrument x, when you iterate over l to get the sum you are accessing the global l variable.

Upvotes: 1

Ohad Sharet
Ohad Sharet

Reputation: 1142

this should do the trick:

l=[1,3,4,5,6,7],[1,1],[1,9,9]
nl= [("sum",len(lst)) for lst in l]
print(nl)

output:

[('sum', 6), ('sum', 2), ('sum', 3)]

if you have any question about the code feel free to ask me in the comments :)

Upvotes: 1

Related Questions