按顺序遍历列表的每个值,从随机值开始
Iterate through each value of list in order, starting at random value
给定以下代码:
length = 10
numbers = [x for x in range(length)]
start_index = randint(0,length-1)
# now output each value in order from start to start-1 (or end)
# ex. if start = 3 --> output = 3,4,5,6,7,8,9,0,1,2
# ex if start = 9 ---> output = 9,0,1,2,3,4,5,6,7,8
遍历列表并按顺序打印每个值的最好/最简单/最pythonic/最酷的方法是什么,从 start 开始并包装到 start-1 或如果随机值为 0 则结束。
例如。 start = 3
然后输出 = 3,4,5,6,7,8,9,1,2
我能想到一些丑陋的方法(尝试,例如 IndexError 除外)但正在寻找更好的方法。谢谢!
编辑:更清楚地说明 start 是开始于
的索引值
>>> start = randint(0, len(numbers))
>>> start
1
您可以使用列表切片然后对其进行迭代
>>> numbers[start:] + numbers[:start]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
您还可以在列表理解中使用取模 %
运算符
>>> [numbers[i%len(numbers)] for i in range(start, start + len(numbers))]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
您应该使用 %
(取模)运算符。
length = 10
numbers = [x for x in range(length)]
start = randint(0, length)
for i in range(length):
n = numbers[(i + start) % length]
print(n)
What is the best / simplest / most pythonic / coolest way ...
你可以使用collections.deque
and its rotate
函数,像这样
>>> from collections import deque
>>> d = deque(numbers)
>>> d.rotate(-9)
>>> d
deque([9, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>>
>>> d = deque(numbers)
>>> d.rotate(-2)
>>> d
deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
您可以尝试使用简单的条件循环遍历列表
i = start
while(True):
print i,
if i==numbers[-1]: # If it's the last number
i=numbers[0]
else:
i += 1
if i==start: # One iteration is over
break
这将打印 3 4 5 6 7 8 9 0 1 2
给定以下代码:
length = 10
numbers = [x for x in range(length)]
start_index = randint(0,length-1)
# now output each value in order from start to start-1 (or end)
# ex. if start = 3 --> output = 3,4,5,6,7,8,9,0,1,2
# ex if start = 9 ---> output = 9,0,1,2,3,4,5,6,7,8
遍历列表并按顺序打印每个值的最好/最简单/最pythonic/最酷的方法是什么,从 start 开始并包装到 start-1 或如果随机值为 0 则结束。
例如。 start = 3
然后输出 = 3,4,5,6,7,8,9,1,2
我能想到一些丑陋的方法(尝试,例如 IndexError 除外)但正在寻找更好的方法。谢谢!
编辑:更清楚地说明 start 是开始于
的索引值>>> start = randint(0, len(numbers))
>>> start
1
您可以使用列表切片然后对其进行迭代
>>> numbers[start:] + numbers[:start]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
您还可以在列表理解中使用取模 %
运算符
>>> [numbers[i%len(numbers)] for i in range(start, start + len(numbers))]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
您应该使用 %
(取模)运算符。
length = 10
numbers = [x for x in range(length)]
start = randint(0, length)
for i in range(length):
n = numbers[(i + start) % length]
print(n)
What is the best / simplest / most pythonic / coolest way ...
你可以使用collections.deque
and its rotate
函数,像这样
>>> from collections import deque
>>> d = deque(numbers)
>>> d.rotate(-9)
>>> d
deque([9, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>>
>>> d = deque(numbers)
>>> d.rotate(-2)
>>> d
deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
您可以尝试使用简单的条件循环遍历列表
i = start
while(True):
print i,
if i==numbers[-1]: # If it's the last number
i=numbers[0]
else:
i += 1
if i==start: # One iteration is over
break
这将打印 3 4 5 6 7 8 9 0 1 2