I'm trying to convert a very basic statement, like this
我试图转换一个非常基本的声明,像这样
for i in the_list:
work.append(i)
y = y[1:]
From a for
loop, to a while
loop. I use code like this a lot and have been trying to learn about different ways to write it, without a for loop.
从for循环到while循环。我使用这样的代码很多,并且一直试图了解不同的编写方式,没有for循环。
2 个解决方案
#1
One way to do this would be:
一种方法是:
i, length = 0, len(the_list)
while i < length:
work.append(i)
y = y[1:]
i += 1
Note: this is not recommended, the for
loop would be considered more Pythonic - it is both shorter and more readable.
注意:不建议这样做,for循环会被认为更Pythonic - 它更短,更易读。
#2
Well if the intention is to just remove the loop then, list comprehension is also a good option
好吧,如果打算只删除循环,列表理解也是一个不错的选择
work =[i for i in the_list]
#1
One way to do this would be:
一种方法是:
i, length = 0, len(the_list)
while i < length:
work.append(i)
y = y[1:]
i += 1
Note: this is not recommended, the for
loop would be considered more Pythonic - it is both shorter and more readable.
注意:不建议这样做,for循环会被认为更Pythonic - 它更短,更易读。
#2
Well if the intention is to just remove the loop then, list comprehension is also a good option
好吧,如果打算只删除循环,列表理解也是一个不错的选择
work =[i for i in the_list]