嵌套for循环以列出具有不同"if"的理解.使适应 [英] nested for loops to list comprehension with differents "if" conditions

查看:74
本文介绍了嵌套for循环以列出具有不同"if"的理解.使适应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此嵌套循环转换为列表理解,但我不确定是否可能,因为"tmp"列表中的项可能有不同的值.这是最好的方法吗?谢谢!

I'm trying to convert this nested loop into a list comprehension but i'm not sure it's possible as there is different values possible for item in "tmp" list. Is it the best way to do this ? Thanks !

final = []
for a in range(-13, 1):
    for b in range(0,4):
        for c in range(6, 49):
            for d in range(48, 94):
                tmp = [0 for i in range(100)]
                for i in range(100):
                    if raw_x[i] >= b and raw_y[i] >= d:
                        tmp [i] = -1
                    if raw_x[i] <= a and raw_y[i] <= c:
                        tmp [i] = 1
                final.append(tmp)

推荐答案

尽管我不确定可读性是否得到改善,但这可以用一个表达式完成:

This can be done in one expression although I'm not sure readability is improved:

final = [
    [
        +1 if x <= a and y <= c
        else -1 if x >= b and y >= d
        else 0
        for x, y in zip( raw_x, raw_y )
    ]
    for a in range(-13, 1)
    for b in range(0, 4)
    for c in range(6, 49)
    for d in range(48, 94)
]

请注意,我假设您要遍历 raw_x raw_y 整个,而不是每次都精确地包含100个元素:这个问题意味着每次都会有100次,但是如果意图是要遍历整个序列,那么最好不要在那里硬编码100次.如果我对意图不正确,则可以将范围内的 for 循环更改为range(100)中的i的 for并使用 raw_x [i] raw_y [i] ,而不是 x y .

Note that I've assumed you want to go through the whole of raw_x and raw_y rather than exactly 100 elements every time: the question implies 100-every-time but if the intention is really to go through the whole sequence, then it's better not to hard-code the 100 in there. If I'm wrong about the intention, you can change that inner-comprehension for loop to for i in range(100) and use raw_x[i] and raw_y[i] in the conditional expression instead of x and y.

这篇关于嵌套for循环以列出具有不同"if"的理解.使适应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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