问题
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 ?
回答1:
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
来源:https://stackoverflow.com/questions/28611994/two-for-loops-in-list-comprehension-python