在列表理解中使用"while"循环 [英] Using 'while' loops in a list comprehension

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

问题描述

说我有一个功能:

x=[]
i=5
while i<=20:
     x.append(i)
     i=i+10
return x

有没有办法像这样将其转换为列表理解?

Is there a way to convert it to a list comprehension like this?

newList = [i=05 while i<=20 i=i+10]

我收到语法错误.

推荐答案

您不需要列表列表. range 会执行以下操作:

You don't need a list comprehension for that. range will just do:

list(range(5, 21, 10)) # [5, 15]

在列表理解内不可能执行 while 循环.相反,您可以执行以下操作:

A while loop is not possible inside of a list comprehension. Instead, you could do something like this:

def your_while_generator():
    i = 5
    while i <= 20:
        yield i
        i += 10

[i for i in your_while_generator()]

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

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