简体   繁体   English

将列表理解转换为 while 循环

[英]Turn list comprehension to while loop

I have the following line of code:我有以下代码行:

mass_grouped3['records_to_select'] = [math.ceil(int((el * target) / freq_sum)) if el > 6 else el for el in mass_grouped3['freq']]

I want to rewrite it with while loop, but don't have much experience with while loops and find it difficult.我想用 while 循环重写它,但对 while 循环没有太多经验,觉得很难。 This is what I have for now, but is not working for some reason:这是我现在所拥有的,但由于某种原因无法正常工作:

trgt = 0
while trgt <= 7500:
    if trgt == 7500:
        break
    else:
        for el in mass_grouped3['freq']:
            if el > 6:
                mass_grouped3['records_to_select'] = [math.ceil(int((el * target) / freq_sum))]
                trgt += 1
            else:
                pass

I want to do the same, but when the counter hit 7500 to break.我也想做同样的事,但是当柜台打到7500就破了。

One thing you could do is just wrap the list comprehension with the while loop which should help avoid length issues.您可以做的一件事就是用 while 循环包装列表理解,这应该有助于避免长度问题。 I'm not sure if target is supposed to be trgt in the second block of code you posted in math.ceil(int((el * trgt) / freq_sum)) so tell me and I'll edit it as needed.我不确定target是否应该是您在trgt math.ceil(int((el * trgt) / freq_sum))中发布的第二个代码块中的 trgt,所以请告诉我,我会根据需要对其进行编辑。

trgt = 0
while trgt < 7500:
    mass_grouped3['records_to_select'] = [math.ceil(int((el * trgt) / freq_sum)) 
                                              if el > 6 else el for el 
                                              in mass_grouped3['freq']]
    trgt += 1

To answer more generally: In general a list comprehension of the form更一般地回答:一般来说,表格的列表理解

result = [foo(a) for a in as if condition]

can be written as a for loop of the form可以写为形式的 for 循环

result = []
for a in as:
    if condition:
        result.append(foo(a))

and in general for loops can be rewritten as while loops, though the exact transformation will depend on the form of the for loop and the structure you're looping over.并且通常 for 循环可以重写为 while 循环,尽管确切的转换将取决于 for 循环的形式和您循环的结构。 If you're looping over a serially-indexed collection like a list, you could generally do:如果你正在循环一个像列表这样的序列索引集合,你通常可以这样做:

result = []
ix = 0
end = len(as)
while ix < end:
    if condition:
        result.append(foo(as[ix]))

and expect to get the same result as the original comprehension.并期望得到与原始理解相同的结果。

Note: the gymnastics that I have to go through and the questions I have to ask in order to do these rewrites serve as a good argument for the use of list comprehensions when possible, and a good guide to when they're possible.注意:我必须通过 go 的体操以及为了进行这些重写而必须提出的问题,这可以作为在可能时使用列表推导的一个很好的论据,并在它们可能的情况下提供一个很好的指南。

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

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