简体   繁体   English

Double for循环到Python列表理解

[英]Double for loop to Python list comprehension

I have the following (simplified structure): 我有以下内容(简化的结构):

class Wafer:
    def __init__(self, df):
        self.dose_fields = df

class Data:
    def __init__(self, add_zero):
        self.wafers = []
        self.wafers.append(Wafer([1.0, 1.5]))
        self.wafers.append(Wafer([2.0, 2.0]))
        self.wafers.append(Wafer([3.0, 3.5]))
        self.wafers.append(Wafer([4.0, 4.5]))

        if add_zero:
            self.wafers.append(Wafer([5.0, 0.0]))

I want to have a function that returns False when there is a zero in one of the dose_fields values. 我希望有一个函数,在其中某个dose_fields值中为零时返回False。

like this: 像这样:

data = Data(True)        
res = True
for wafer in data.wafers:
    for fld in wafer.dose_fields:
        if fld == 0.0:
            res = False
print res

data = Data(False)        
res = True
for wafer in data.wafers:
    for fld in wafer.dose_fields:
        if fld == 0.0:
            res = False
print res

This prints False resp. 这将打印False响应。 True (what I want). 正确(我想要的)。

However, when I try to use list comprehension: 但是,当我尝试使用列表理解时:

data = Data(True)
print [df for df in wafer.dose_fields for wafer in data.wafers]
print res

data = Data(False)
print [df for df in wafer.dose_fields for wafer in data.wafers]
print res

I get the result 我得到结果

[4.0, 4.0, 4.0, 4.0, 4.0, 4.5, 4.5, 4.5, 4.5, 4.5]
True

resp 回应

[5.0, 5.0, 5.0, 5.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0]
True

Somehow I get repeats of the last item, while I want the complete list and check afterwards if there is a 0.0 inside. 不知何故,我得到了最后一项的重复,而我想要完整的列表,然后检查里面是否有0.0。

What should I do to 'repair' the list comprehension statement? 我应该怎么做才能“修复”列表理解语句?

Nested list comprehensions can be a bit confusing. 嵌套列表的理解可能会有些混乱。 You actually need to write them in the same order as the for loops they replace: so it should be 实际上,您实际上需要按照与其替换的for循环相同的顺序来编写它们:

[df for wafer in data.wafers for df in wafer.dose_fields]

If testing for the presence of 0.0 is really all you want, you should use the in operator. 如果真的需要测试是否存在0.0 ,则应使用in运算符。 Not only is it far more readable, it's much faster. 它不仅更具可读性,而且速度更快。 You can then use any , too 然后,您也可以使用any

Instead of: 代替:

res = True
for wafer in data.wafers:
    for fld in wafer.dose_fields:
        if fld == 0.0:
            res = False

do

res= not any([0.0 in wafer.dose_fields for wafer in data.wafers])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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