[英]Reversing arrays in 2D arrays in Python
I have a question wether it is possible to reverse certain arrays in my 2D array.我有一个问题,是否可以反转我的二维数组中的某些数组。 For example
例如
a=[[1,2],[3,4],[5,6]]
a[1:3].reverse()
print(a)
would output:会输出:
[1,2],[5,6],[3,4]
I hope you can help :)我希望你能帮助:)
a = [[1, 2], [3, 4], [5, 6]]
a = a[:1] + list(reversed(a[1:3]))
print(a)
You could also use pure slicing, but imo the previous version is more readable:您也可以使用纯切片,但 imo 以前的版本更具可读性:
a = a[:1] + a[:-3:-1]
Your code is actually reversing a copy, and not changing the underlying array.您的代码实际上是在反转副本,而不是更改底层数组。
I'd do this:我会这样做:
a[1:3] = reversed(a[1:3])
It takes a reversed copy of the elements from 1 to three and puts them into their initial locations.它需要从 1 到 3 的元素的反向副本,并将它们放入它们的初始位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.