无限循环列表

时间:2019-03-28 15:47:15

标签: python python-3.x list

a = 1
b = 2
c = 3
x = a

def change_x():
    x = next??
    print("x:", x)

for i in range(10):
    change_x()

我如何无限期地调用change_x()来遍历a,b,c?

输出应为:

x: 2
x: 3
x: 1
x: 2
...

7 个答案:

答案 0 :(得分:8)

您可以使用itertools.cycle来循环遍历abc中指定的值:

from itertools import cycle
for i in cycle([a,b,c]):
    print(f'x: {i}')

输出

x: 1
x: 2
x: 0
x: 1
x: 2
x: 0
x: 1
x: 2
x: 0
x: 1
...

答案 1 :(得分:8)

您可以使用cycle()并调用next()多次,以获取循环值。

from itertools import cycle

values = [1, 2, 3]
c = cycle(values)

for _ in range(10):
    print(next(c))

输出:

1
2
3
1
2
3
1
2
3
1

或如@chepner建议的那样,不使用next()

from itertools import islice

for i in islice(c, 10):
    print(i)

要获得相同的结果。

答案 2 :(得分:3)

itertools.cycle就是这样

import itertools,time

for i in itertools.cycle([1,2,3]):
    print(i)
    time.sleep(1)

答案 3 :(得分:2)

只需将您的变量放在列表中,然后按以下方式选择它们即可:

mylist = [a,b,c]
i=0
while True:
   print(mylist[i%3])
   i+=1

答案 4 :(得分:1)

如果要手动定义函数,请使用yield from

def cycle(iterables):
    while True:
        yield from iterables

答案 5 :(得分:0)

我不确定您是否打算以这种方式使用全局环境变量,但是可以按照您使用对象的方式进行操作。

这是假设您知道变量的名称,以便您可以使用globals()来访问变量的值。

class CycleThrough:
    def __init__(self, variable_list = ['a','b','c']):
        self.variable_list = variable_list
        self.current_variable_idx = 0
        self.total_length = len(self.variable_list)

    def next_variable(self):
        new_index = self.current_variable_idx + 1
        if new_index == self.total_length:
            new_index = 0 

        self.current_variable_idx = new_index

        variable_name = self.variable_list[self.current_variable_idx]


        global x 
        x = globals()[variable_name]
        print(x)

# defining your variables
a = 1
b = 2
c = 3 
x = a

#use object method to cycle through and reassign the global variable x

ct = CycleThrough()
for i in range(10):
    ct.next_variable()

答案 6 :(得分:0)

如果要使用不使用itertools的替代项,则可以创建一个返回要循环的列表的类,然后在循环中可以打印该列表,如以下代码所示:

class Repeater:
    def __init__(self, l):
        self.l = l
    def __iter__(self):
        return self
    def __next__(self):
        return self.l

l = Repeater([1, 2, 3])

for e in l:
    print(*[f"x: {i}" for i in e], sep='\n')

我假设您使用的是Python 3.6+,否则,请将print语句更改为:

print(*["x: {}".format(i) for i in e], sep='\n')

输出:

x: 1
x: 2
x: 3
x: 1
x: 2
x: 3
x: 1
x: 2
x: 3
x: 1
x: 2
x: 3
x: 1