[英]Add column to 2D array in Python
我正在嘗試在Python的2D數組中添加額外的列,但我遇到了麻煩。 我有一個二維數組,如下所示:
['000', '101']
['001', '010']
['010', '000']
['011', '100']
然后,我從第二列交換2個元素,並得到如下內容:
['000', '101']
['001', '000']
['010', '010']
['011', '100']
我現在想拿最后一列,並將其添加為第三列,如下所示:
['000', '101', '101']
['001', '010', '000']
['010', '000', '010']
['011', '100', '100']
但是我只能做到這一點:
['000', '101']
['001', '000']
['010', '010']
['011', '100']
101
000
010
100
我正在添加這樣的列:
col = column(data,1)
data_res += col
我正在創建這樣的數組:
with open('data.txt', 'r') as f:
for line in f:
line_el = line.split()
data.append(line_el)
我這樣交換:
def swap(matrix, id_l, id_r):
matrix[id_l][1], matrix[id_r][1] = matrix[id_r][1],matrix[id_l][1]
return matrix
有任何想法嗎?
由於您將2D列表寫為列表列表( Row Major Order ),因此添加列意味着向每行添加一個條目。
看來您已經創建了一些數據,如下所示:
# Create a 2D list
data = [['000', '101'],['001', '010'],['010', '000'],['011', '100']]
因此,現在您可以添加一個與最后一列相同的新列,如下所示:
# Loop through all the rows
for row in data:
lastColumn = row[-1]
# Now add the new column to the current row
row.append(lastColumn)
列表理解可以快速做到這一點。 這段代碼不會執行交換,但是看起來您已經在工作。 :)
data = [['000', '101'],['001', '010'],['010', '000'],['011', '100']]
print [x + [x[1]] for x in data]
# [
# ['000', '101', '101'],
# ['001', '010', '010'],
# ['010', '000', '000'],
# ['011', '100', '100']
# ]
with open('data.txt', 'r') as f:
for line in f:
line_el = line.split()
data.append([x + [x[1]] for x in line_el])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.