在python中使用自定义步骤循环 [英] For loop with custom steps in python
问题描述
我可以在 python 中创建简单的 for 循环,例如:
I can make simple for loops in python like:
for i in range(10):
然而,我不知道如何制作更复杂的,这在 C++ 中真的很容易.
However, I couldn't figure out how to make more complex ones, which are really easy in c++.
你将如何在 python 中实现这样的 for 循环:
How would you implement a for loop like this in python:
for(w = n; w > 1; w = w / 2)
迄今为止我制作的最接近的一个是:
The closest one I made so far is:
for w in reversed(range(len(list)))
推荐答案
首先也是最重要的:Python for
循环与 C for
循环实际上并不是一回事.它们是 For Each 循环.您迭代可迭代的元素.range()
生成一个可迭代的整数序列,让您模拟最常见的 C for
循环用例.
First and foremost: Python for
loops are not really the same thing as a C for
loop. They are For Each loops instead. You iterate over the elements of an iterable. range()
generates an iterable sequence of integers, letting you emulate the most common C for
loop use case.
然而,大多数时候您不想想要使用range()
.您将遍历列表本身:
However, most of the time you do not want to use range()
. You would loop over the list itself:
for elem in reversed(some_list):
# elem is a list value
如果必须要有索引,通常使用enumerate()
将其添加到循环中:
If you have to have a index, you usually use enumerate()
to add it to the loop:
for i, elem in reversed(enumerate(some_list)):
# elem is a list value, i is it's index in the list
对于真正时髦"的循环,使用 while
或创建您自己的生成器函数:
For really 'funky' loops, use while
or create your own generator function:
def halved_loop(n):
while n > 1:
yield n
n //= 2
for i in halved_loop(10):
print i
打印10
、5
、2
.您也可以将其扩展到序列:
to print 10
, 5
, 2
. You can extend that to sequences too:
def halved_loop(sequence):
n = -1
while True:
try:
yield sequence[n]
except IndexError:
return
n *= 2
for elem in halved_loop(['foo', 'bar', 'baz', 'quu', 'spam', 'ham', 'monty', 'python']):
print elem
打印:
python
monty
spam
foo
这篇关于在python中使用自定义步骤循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!