在python中使用自定义步骤进行循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17944235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For loop with custom steps in python
提问by gen
I can make simple for loops in python like:
我可以在 python 中简化 for 循环,例如:
for i in range(10):
However, I couldn't figure out how to make more complex ones, which are really easy in c++.
但是,我不知道如何制作更复杂的,这在 C++ 中真的很容易。
How would you implement a for loop like this in python:
你将如何在 python 中实现这样的 for 循环:
for(w = n; w > 1; w = w / 2)
The closest one I made so far is:
到目前为止,我制作的最接近的一个是:
for w in reversed(range(len(list)))
采纳答案by Martijn Pieters
First and foremost: Python for
loops are not really the same thing as a C for
loop. They are For Each loopsinstead. 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.
首先也是最重要的:Pythonfor
循环与 Cfor
循环并不是一回事。它们是For Each 循环。您迭代可迭代的元素。range()
生成一个可迭代的整数序列,让您模拟最常见的 Cfor
循环用例。
However, most of the time you do notwant to use range()
. You would loop over the list itself:
然而,大多数的时候你不希望使用range()
。您将遍历列表本身:
for elem in reversed(some_list):
# elem is a list value
If you have to have a index, you usually use enumerate()
to add it to the loop:
如果必须要有索引,通常使用enumerate()
将其添加到循环中:
for i, elem in reversed(enumerate(some_list)):
# elem is a list value, i is it's index in the list
For really 'funky' loops, use while
or create your own generator function:
对于真正“时髦”的循环,请使用while
或创建您自己的生成器函数:
def halved_loop(n):
while n > 1:
yield n
n //= 2
for i in halved_loop(10):
print i
to print 10
, 5
, 2
. You can extend that to sequences too:
打印10
, 5
, 2
. 您也可以将其扩展到序列:
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
which prints:
打印:
python
monty
spam
foo
回答by the5fire
for i in range(0, 10, 2):
print(i)
>>> 0
>>> 2
>>> 4
>>> 6
>>> 8
http://docs.python.org/2/library/functions.html
http://docs.python.org/2/library/functions.html
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
回答by Atmaram Shetye
Something like for i in [n/(2**j) for j in range(int(math.log(n))+1)]
就像是 for i in [n/(2**j) for j in range(int(math.log(n))+1)]
回答by Daniel Roseman
For your exact example, you probably wouldn't use a for loop at all, but a while loop:
对于您的确切示例,您可能根本不会使用 for 循环,而是使用 while 循环:
w = n
while w > 1:
do stuff
w = w / 2
回答by Shree Kumar
You need to use a generator. You could implement this as follows:
您需要使用发电机。您可以按如下方式实现:
def stepDown(n):
while n>1:
yield n
n = n/2
for i in stepDown(n):
print i # or do whatever else you wish.
Note that this generalizes easily to other complicated patterns you may have in mind.
请注意,这很容易推广到您可能想到的其他复杂模式。
回答by tobias_k
For the more general case, you could create a custom generator function, that takes a start
, stop
, and a function for generating the next step from the last:
对于更一般的情况下,你可以创建一个自定义生成功能,采用一个start
,stop
以及生成从上下一步的功能:
def my_range(start, stop, f):
x = start
while x < stop if stop > start else x > stop:
yield x
x = f(x)
>>> list(my_range(1, 1024, lambda x: x*2))
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
>>> list(my_range(1000, 1, lambda x: x/2))
[1000, 500.0, 250.0, 125.0, 62.5, 31.25, 15.625, 7.8125, 3.90625, 1.953125]