4

几天前我开始学习 Python,在编写代码时遇到了一个程序。

这是我想使用 C++ 代码做的事情

number = SOME_NUMBER;
while(1) {
    for(int i=number; i<sizeOfArray; i++) {
        // do something
    }
    number = 0;
}

基本上,对于我的 for 循环的第一次迭代,我想从数字开始。然后每隔一次我通过for循环,我想从0开始。

我现在能想到的一种 hacky 想法是:

number = SOME_NUMBER
for i in range(0, len(array)):
    if i != number:
        continue
    // do something

while True:
    for i in range(0, len(array)):
        // do something

这是最好的方法还是有更好的方法?

4

3 回答 3

7

what is the problem with this?

starting_num = SOME_NUMBER
while True:
    for i in xrange(starting_num, len(array)):
        # do code
    starting_num = 0

it does exactly what you want.

however, i think there are better ways to do things especially if the solution seems "hacky".

if you gave an idea of what you wanted to do, maybe there is a better way

于 2012-12-27T11:14:07.950 回答
2

I don't see why you couldn't just do the same thing you are in C:

number = SOME_NUMBER
while True:
    for i in range(number, len(array)):
        # do something
    number = 0

BTW, depending on which version of Python you're using, xrange may be preferable over range. In Python 2.x, range will produce an actual list of all the numbers. xrange will produce an iterator, and consumes far less memory when the range is large.

于 2012-12-27T11:14:29.563 回答
1

在 Python 中,跨过传统意义上的集合并不理想。循环 - 迭代 - 对象的能力由对象控制,因此您无需像for在 C++ 中的循环中那样手动单步执行计数器。

据我了解,您在这里尝试做的是多次对a 中的每个项目执行相同的代码list(Python 中没有数组)。

要做到这一点:

def whatever_function(foo):
   # some code here that works on each item on the list
   # foo is an item of the list

while True:
   map(whatever_function, some_list)
于 2012-12-27T11:18:57.553 回答