简体   繁体   English

在二维列表中交换两列

[英]Swapping two columns in a 2D list

what would be the quickest way to get to : 最快的方法是:

[[0, 2, 0, 0],\
[0, 2, 0, 0],\
[0, 2, 0, 0],\
[0, 2, 0, 0]]

from: 从:

[[0, 0, 2, 0],\
[0, 0, 2, 0],\
[0, 0, 2, 0],\
[0, 0, 2, 0]]

without using numpy or any other external library 无需使用numpy或任何其他外部库

Let's say we have a list l , which is [0, 0, 2, 0] , and we want to shift all the elements one place to left. 假设我们有一个列表l ,它是[0, 0, 2, 0] ,我们想将所有元素向左移动一位。

Firstly, we need to get all the elements to the right except the first one. 首先,我们需要将除第一个元素之外的所有元素都移到右边。 List slicing l[1:] would work here, which would get [0, 2, 0] . 列表切片l[1:]在这里可以工作,它将得到[0, 2, 0]

Secondly, we need to get the remaining elements on the left with l[1:] , which would get [0] . 其次,我们需要使用l[1:]来获得左侧的其余元素,该元素将获得[0]

You can now probably see that we can shift the elements one place to the left with adding the above 2 lists together: 现在您可能已经看到,通过将上述两个列表加在一起,可以将元素向左移动一个位置:

>>> lst = [0, 0, 2, 0]
>>> first = lst[1:]
>>> second = lst[:1]
>>> first + second
[0, 2, 0, 0]

Which can be summarized in this function: 可以总结为以下功能:

def shift(lst, n):
    return lst[n:] + lst[:n]

Since this can shift one lists position, it can applied to all lists in a nested list and shift their positions to left by 1: 由于这可以移动一个列表的位置,因此可以将其应用于嵌套列表中的所有列表,并将其位置向左移动1:

nested_lst = [shift(sublist, 1) for sublist in nested_lst]

For your specific task: 对于您的特定任务:

l = [[0, 2, 0, 0], [0, 2, 0, 0], [0, 2, 0, 0], [0, 2, 0, 0]]

for arr in l:
    arr[1], arr[2] = arr[2], arr[1]

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

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