将嵌套循环和条件转换为列表理解 [英] Convert nested loops and conditions to a list comprehension

查看:59
本文介绍了将嵌套循环和条件转换为列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表是否有一种理解此条件集的方法.

Is there a way for list comprehending this condition set.

clamp_sel = list()
for i in range(0, len(clamp_normalized)):
        for j in range(0, len(clamp_normalized[i])):
                if clamp_normalized[i][j][0] < int(max_min_band[index_selec]):
                        clamp_sel.append(int(clamp_normalized[i][j][0]))

如果是一维列表,我可以通过这种方式设置条件.

If it is single dimension list, I could set the condition in this way.

norm_sel = [i for i in normalize_data if i[0] > max_min_band[index_selec]]

谢谢

推荐答案

这应直接转换为列表理解:

This should translate directly into a list-comprehension:

clamp_sel = [int(clamp_normalized[i][j][0])
    for i in range(0, len(clamp_normalized))
    for j in range(0, len(clamp_normalized[i]))
    if clamp_normalized[i][j][0] < int(max_min_band[index_selec])]

一般规则是(请参见手册)您应该以与一系列嵌套的for循环和if语句完全相同的顺序编写list-comprehension.唯一要更改的是将最终的xx.append(yy)用列表理解的最前面的yy替换.还要注意,这本质上是一个长表达式,您可以在很长的一行上编写.由于包含[],因此您可以将该表达式分为任意多缩进的多行.

The general rule is (see the manual) that you should write the list-comprehension in exactly the same order as you would do with a series of nested for loops and if-statements. The only thing you change is to replace the final xx.append(yy) with just yy at the front of the list comprehension. Also note that this is essentially one long expression that you could write on an extremely long line. Because of the enclosing [], you can divide this expression over multiple lines, with arbitrary indentation.

如果列表理解度比原始理解度更 pythonic ,那么这是一个品味问题.在这种情况下,嵌套很简单,所以我个人会去进行列表理解.如果变得更加复杂,请遵循for循环.

If the list-comprehension is more pythonic than the original is a question of taste. In this case, the nesting is straightforward, so I would personally go for the list-comprehension. If it gets more complex, stick to the for-loops.

正如thefourtheye所示,可以通过在列表上进行直接迭代来代替range()的使用,从而进一步简化此示例.

As thefourtheye shows, this example can be further simplified by replacing the use of range() with a direct iteration over your lists.

这篇关于将嵌套循环和条件转换为列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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