用python中的自定义步骤循环 [英] For loop with custom steps in python

查看:108
本文介绍了用python中的自定义步骤循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在python中简化循环,例如:

pre $ 为范围(10):

然而,我不知道如何制作更复杂的,在c ++中非常简单。



你将如何在Python中实现一个for循环:

  for(w = n; w> 1; w = w / 2)

是:

pre $ for w in reverse(range(len(list)))


解决方案

首先:Python for 与C for 循环完全相同。他们是 For Each loops 。你迭代迭代的元素。 range()产生一个可迭代的整数序列,可以让你模拟循环用例中最常用的C 但是,大多数情况下,您不是要使用 range()。您可以在列表中循环:

$ p $ for elem in(some_list):
#elem是一个列表值

如果必须有索引,通常使用 enumerate() / code>将其添加到循环中:

  for i,elem in reversed(enumerate(some_list)): 
#elem是一个列表值,我是它的列表中的索引

时髦的循环,使用或创建自己的生成器函数:

pre $ def halved_loop(n):
while n> 1:
产生n
n // = 2

在halved_loop(10)中:i
print i

打印 10 5 2 。你可以扩展到序列:

  def halved_loop(sequence):
n = -1
while True:
try:
yield order [n]
除了IndexError:
返回
n * = 2

为halved_loop([ 'foo','bar','baz','quu','spam','ham','monty','python']):
print elem




$ b $ p $ python
monty
spam
foo


I can make simple for loops in python like:

for i in range(10):

However, I couldn't figure out how to make more complex ones, which are really easy in c++.

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)))

解决方案

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.

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

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

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

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

which prints:

python
monty
spam
foo

这篇关于用python中的自定义步骤循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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