Reputation: 11
Hi I am learning list comprehension in Python and I got myself a 2 dimensional list of strings:
a="agagaffsst555s5s"
b="jkkjsd675sggd"
c="flflfkisisud787782ssa"
d="glgjdusgygd4562381djakughduiytywy"
e="hjashjyyd665656452hhf"
f="687255365165417gsafvx7787878"
mylist=[[a,b],[c,d,e],[f,a,d],[d]]
And now I would like to get a list mylist2
of the same dimension as mylist
but containing sums of characters of all the strings in sublists, so that:
mylist2[0]=len(mylist[0][0]) + len(mylist[0][1])
I tried writing a comprehension:
mylist2=[sum(len(mylist[i][j])) for j in range(len(mylist[i])) for i in range(len(mylist))]
and it doesn't work. I guess I am using sum
function wrongly as well
Upvotes: 0
Views: 115
Reputation: 12704
I will join each items in the list and get the length.
mylist=[[a,b],[c,d,e],[f,a,d],[d]]
mylist2=[len(''.join(i)) for i in mylist]
mylist2
Result:
[29, 75, 77, 33]
Upvotes: 0
Reputation: 39072
Use nested list comprehension. Then, take the sum of elements in each sublist to get the corresponding total number of characters. Furthermore, I am presenting a shorter simplified version without using range(len(...))
. You can directly loop over the list elements
mylist2 = [sum([len(j) for j in subl]) for subl in mylist]
# [29, 75, 77, 33]
If you don't want the sum, then just remove the sum()
command
mylist2 = [[len(j) for j in subl] for subl in mylist]
# [[16, 13], [21, 33, 21], [28, 16, 33], [33]]
Upvotes: 1
Reputation: 6935
Try this :
mylist2 = list(list(map(len, i)) for i in mylist)
Output :
[[16, 13], [21, 33, 21], [28, 16, 33], [33]]
To get the sum for each sub-list :
mylist2 = list(sum(list(map(len, i))) for i in mylist)
Output :
[29, 75, 77, 33]
Upvotes: 0