列表理解python中的两个for循环 [英] two for loops in list comprehension python

查看:62
本文介绍了列表理解python中的两个for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

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]])

列表理解循环以嵌套顺序列出,从左到右与在常规Python循环中嵌套相同:

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]:

这仍然不起作用,因为 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)

演示:

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

这篇关于列表理解python中的两个for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆