如何在Python中循环遍历列表?

6
假设我从以下列表 [a,b,c] 开始,并且我想要创建包含原始列表的所有循环的以下列表 [[a,b,c], [c,a,b], [b,c,a]]。如何以最高效的方式完成?

你试试看? - Druta Ruslan
我可以定义一个函数来旋转一个列表 def rotate(l, n): return l[n:] + l[:n] 但对我来说,似乎应该有更有效的方法来做到这一点。 - Turbotanten
你只是在寻找列表的排列吗?循环通常指的是其他东西。 - Carcigenicate
2个回答

6

使用列表推导式或者你需要一些特别的东西?

lst = ['a','b','c']

n_lst = [lst[x:] + lst[:x] for x in range(len(lst))]
print(n_lst)

输出

[['a', 'b', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b']]

为所有排列提供特殊服务

import itertools
list(itertools.permutations(lst))

输出

[
  ('a', 'b', 'c'), 
  ('a', 'c', 'b'), 
  ('b', 'a', 'c'), 
  ('b', 'c', 'a'), 
  ('c', 'a', 'b'), 
  ('c', 'b', 'a')
]

此外,我检查了 @jpp 回答中 list comprehensioncollections.deque 对象中的内置函数rotate的执行时间。

lst = list(range(10000))

# list comprehension time
1.923051118850708

# rotate from collections.deque time
1.6390318870544434

旋转操作速度更快。


3
使用 collections.deque 和其中的方法 rotate
from collections import deque

A = deque(['a', 'b', 'c'])

res = []
for i in range(len(A)):
    A.rotate()
    res.append(list(A))

print(res)

[['c', 'a', 'b'],
 ['b', 'c', 'a'],
 ['a', 'b', 'c']]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接