Reputation: 340
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)))
The output is coming as [('sum', 3), ('sum', 3), ('sum', 3)]
I am trying to get it using list comprehension.
The expected output I want should be [('sum',6),('sum',2),('sum',3)]
Upvotes: 0
Views: 65
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
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
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
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