简体   繁体   English

更改矩阵中的元素顺序(python)

[英]Change elements order in a matrix (python)

mat = [[0],[1],[2]]

I want to "cycle" the element of my matrix like this: 我想像这样“循环”矩阵的元素:

mat = [[2],[0],[1]]
mat = [[1],[2],[0]]
mat = [[0],[1],[2]]
...

How can I change the index of these elements to loop like above? 如何更改这些元素的索引以像上面那样循环?

>>> for i in xrange(len(mat)):
...  print(mat[i:] + mat[:i])
... 
[[0], [1], [2]]
[[1], [2], [0]]
[[2], [0], [1]]

For large lists using a combination of deque and a generator will be most efficient: 对于大型列表,结合使用双端队列生成器将是最有效的:

>>> import collections.deque
>>> def list_cycler_gen(lst):
        q = collections.deque(lst,len(lst))
        while True:
            q.appendleft(q.pop())
            yield list(q)

>>> gen = list_cycler_gen([[0],[1],[2]])
>>> gen.next()
[[2], [0], [1]]
>>> gen.next()
[[1], [2], [0]]
>>> gen.next()
[[0], [1], [2]]

This will work with anything you place in the list. 这将与您在列表中放置的所有内容一起使用。 Also, if you would have wanted to cycle in the other direction, you could replace the first loop line with: 另外,如果您想沿另一个方向循环,则可以将第一条循环线替换为:

q.append(q.popleft())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM