基本上我在python中有一个矩阵'例子' (虽然大得多)。我需要制作阵列' example_what_I_want'用一些python代码。我想for循环是有序的 - 但我怎么能这样做呢?
example=
[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]
example_what_I_want =
[25,24,23,22,21],
[16,17,18,19,20],
[15,14,13,12,11],
[6,7,8,9,10],
[5,4,3,2,1]
所以它以蛇的方式增加。第一行必须颠倒!然后按照那种模式。
谢谢!
答案 0 :(得分:5)
我假设example
实际上是:
example = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
在这种情况下你可以这样做:
swapped_example = [sublst if idx%2 else sublst[::-1] for
idx,sublst in enumerate(example)][::-1]
哪个会给你:
In [5]: swapped_example
Out[5]:
[[25, 24, 23, 22, 21],
[16, 17, 18, 19, 20],
[15, 14, 13, 12, 11],
[6, 7, 8, 9, 10],
[5, 4, 3, 2, 1]]
答案 1 :(得分:1)
或者,你可以使用它。
a = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
b = []
rev_a = iter(a[::-1])
while rev_a:
try:
b.append(rev_a.next()[::-1])
b.append(rev_a.next())
except StopIteration:
break
print b
修改(之前不知道。@ Adam),
a = iter(a)
while a:
try:
b.insert(0, a.next()[::-1])
b.insert(0, a.next())
except StopIteration:
break
print b[::-1]