6 python indexing reverse list range
我试图将列表列表旋转90度.例如,改变这个:
[[1,2,3], [4,5,6], [7,8,9]]
Run Code Online (Sandbox Code Playgroud)
至
[[7,4,1], [8,5,2],[9,6,3]]
Run Code Online (Sandbox Code Playgroud)
视觉:
[[1,2,3], [[7,4,1],
[4,5,6], --> [8,5,2],
[7,8,9]] [9,6,3]]
Run Code Online (Sandbox Code Playgroud)
每当我将列表大小更改为更多元素或更少时,它总是说索引超出范围?到底是怎么回事?
def rotate(list1):
bigList = [] #create a list that we will append on to
for i in (range(len(list1)+1)): #loop through the list looking at the indexes
newList = []
for j in reversed(range(len(list1))): #reverse that list
newList.append(list1[j][i])
bigList.append((newList)) #append the elements to the bigList reversed
return bigList
Run Code Online (Sandbox Code Playgroud)
reversed使用和可以很容易地在一行中完成您正在做的事情zip。本答案下面给出了代码中的实际问题。
例子 -
list(zip(*reversed(yourlist)))
Run Code Online (Sandbox Code Playgroud)
list(...)对于Python 2.x ,您不需要,因为会返回Python 2.xzip()中的列表。
演示 -
>>> list(zip(*reversed([[1,2,3], [4,5,6], [7,8,9]])))
[(7, 4, 1), (8, 5, 2), (9, 6, 3)]
>>> list(zip(*reversed([[1,2,3,4], [5,6,7,8], [9,10,11,12]])))
[(9, 5, 1), (10, 6, 2), (11, 7, 3), (12, 8, 4)]
Run Code Online (Sandbox Code Playgroud)
如果您想要列表的列表,而不是元组的列表,您可以使用列表理解(或map(list, zip(*reversed(....))))。例子 -
[list(x) for x in zip(*reversed(yourlist))]
Run Code Online (Sandbox Code Playgroud)
演示 -
>>> [list(x) for x in zip(*reversed([[1,2,3], [4,5,6], [7,8,9]]))]
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
>>> [list(x) for x in zip(*reversed([[1,2,3,4], [5,6,7,8], [9,10,11,12]]))]
[[9, 5, 1], [10, 6, 2], [11, 7, 3], [12, 8, 4]]
Run Code Online (Sandbox Code Playgroud)
*是 unpacking 的语法,因此返回的列表reversed()被解包zip()并作为单独的参数传递给它。
然后zip()函数将其每个参数的元素组合在其相应的索引处(例如所有第一个参数在一起,所有第二个参数在一起等),因此我们得到了我们需要的结果。
原始代码的实际问题是由于以下行而发生的 -
for i in (range(len(list1)+1)):
Run Code Online (Sandbox Code Playgroud)
您正在循环直到len(list1) + 1,因此最终您尝试访问类似 的元素list1[0][len(list1)],但在您的情况下不存在。
假设list1所有子列表都具有相同数量的元素,那么您真正需要的就是len(list1[0])。例子 -
def rotate(list1):
bigList = [] #create a list that we will append on to
for i in (range(len(list1[0]))): #loop through the list looking at the indexes
newList = []
for j in reversed(range(len(list1))): #reverse that list
newList.append(list1[j][i])
bigList.append((newList)) #append the elements to the bigList reversed
return bigList
Run Code Online (Sandbox Code Playgroud)
演示 -
>>> def rotate(list1):
... bigList = [] #create a list that we will append on to
... for i in (range(len(list1[0]))): #loop through the list looking at the indexes
... newList = []
... for j in reversed(range(len(list1))): #reverse that list
... newList.append(list1[j][i])
... bigList.append((newList)) #append the elements to the bigList reversed
... return bigList
...
>>> rotate([[1,2,3], [4,5,6], [7,8,9]])
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
>>> rotate([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
[[9, 5, 1], [10, 6, 2], [11, 7, 3], [12, 8, 4]]
Run Code Online (Sandbox Code Playgroud)