简体   繁体   中英

two for loops in list comprehension python

I have a list:

f_array=['1000,1','100,10','100,-10']

I am trying to sum up all the first element in each value of the above array. I tried something like:

number = sum([ num for num in item.split(",")[1] for item in f_array])

but it dint work. What would be the best way to do it ?

If you want to use nested loops then need to swap the order of the for loops:

number = sum([num for item in f_array for num in item.split(",")[1]])

List comprehension loops are listed in nesting order , left to right is the same as nesting in regular Python loops:

for item in f_array:
    for num in item.split(",")[1]:

This still won't work, as item.split(',')[1] is a string; you'll end up looping over the characters. If you wanted to sum every second number, just select that number:

item.split(",")[1] for item in f_array

There is no need to loop there as there is no sequence when you selected one element.

You don't actually want to use a list comprehension here; drop the [...] square brackets to make it a generator expression, thus avoiding creating an intermediary list object altogether.

You also need to convert your strings to integers if you wanted to sum them:

number = sum(int(item.split(",")[1]) for item in f_array)

Demo:

>>> f_array = ['1000,1', '100,10', '100,-10']
>>> sum(int(item.split(",")[1]) for item in f_array)
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM