2014-01-13 40 views

回答

5

有了一個for循環,並從this後一點幫助:

代碼:

N = [["D","C","A","B"], 
    [2,3,4,5], 
    [6,7,8,9]] 

# Swap the last two columns 

for item in N: 
    item[2], item[3] = item[3], item[2] 

# Or as a function 

def swap_columns(your_list, pos1, pos2): 
    for item in your_list: 
     item[pos1], item[pos2] = item[pos2], item[pos1] 

輸出:

swap_columns(N, 2, 3) 
[['D', 'C', 'B', 'A'], [2, 3, 5, 4], [6, 7, 9, 8]] 
+0

請注意,這使交換就地......這可能正是想要的! –

1

另一種可能性,使用zip

In [66]: N = [['D', 'C', 'A', 'B'], [2, 3, 4, 5], [6, 7, 8, 9]] 

移調使用zip

In [67]: M = list(zip(*N)) 

交換行1和2:

In [68]: M[1], M[2] = M[2], M[1] 

再次移調:

In [69]: N2 = list(zip(*M)) 

In [70]: N2 
Out[70]: [('D', 'A', 'C', 'B'), (2, 4, 3, 5), (6, 8, 7, 9)] 

結果是元組的列表。如果您需要列表清單:

In [71]: [list(t) for t in zip(*M)] 
Out[71]: [['D', 'A', 'C', 'B'], [2, 4, 3, 5], [6, 8, 7, 9]] 

這並不會使就地交換。爲此,請參閱@ DaveTucker的回答。

+0

'zip'不會返回Python3中的列表 –

+0

@gnibbler:謝謝,忘記了這一點。固定。 –

0
>>> N = [['D','C','A','B'], 
...  [2,3,4,5], 
...  [6,7,8,9]] 
>>> 
>>> lineorder = 0,2,1,3 
>>> 
>>> [[r[x] for x in lineorder] for r in N] 
[['D', 'A', 'C', 'B'], [2, 4, 3, 5], [6, 8, 7, 9]] 

如果你不想順序硬編碼,則可以很容易地生成它像這樣

>>> lineorder = [N[0].index(x) for x in ['D','A','C','B']] 
0

要創建N個副本與交換,S兩列,在一行中,你可以請執行以下操作:

>>> N = [['D','C','A','B'],[2,3,4,5],[6,7,8,9]] 
>>> S = [[n[0],n[2],n[1],n[3]] for n in N] 
>>> S 
[['D', 'A', 'C', 'B'], [2, 4, 3, 5], [6, 8, 7, 9]] 

這假定每個N的嵌套列表的大小相等。