[英]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.