简体   繁体   English

在Python中将列添加到2D数组

[英]Add column to 2D array in Python

I'm trying to add an extra column to a 2D array in Python but I'm stuck. 我正在尝试在Python的2D数组中添加额外的列,但我遇到了麻烦。 I have a 2D array like below: 我有一个二维数组,如下所示:

['000', '101']
['001', '010']
['010', '000']
['011', '100']

Then I swap 2 elements from the 2nd column and have something like this: 然后,我从第二列交换2个元素,并得到如下内容:

['000', '101']
['001', '000']
['010', '010']
['011', '100']

I want to take the last column right now and add it as the 3rd one like this: 我现在想拿最后一列,并将其添加为第三列,如下所示:

['000', '101', '101']
['001', '010', '000']
['010', '000', '010']
['011', '100', '100']

But I only managed to get this: 但是我只能做到这一点:

['000', '101']
['001', '000']
['010', '010']
['011', '100']
101
000
010
100

I'm adding a column like this: 我正在添加这样的列:

col = column(data,1)
data_res += col

I'm creating an array like this: 我正在创建这样的数组:

with open('data.txt', 'r') as f:
     for line in f:
         line_el = line.split()
         data.append(line_el)

I'm swapping like this: 我这样交换:

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

Any ideas? 有任何想法吗?

Since you are writing your 2D list as a list of lists ( Row Major Order ), adding a column means adding an entry to each row. 由于您将2D列表写为列表列表( Row Major Order ),因此添加列意味着向每行添加一个条目。

It seems you already have some data created like this: 看来您已经创建了一些数据,如下所示:

# Create a 2D list
data = [['000', '101'],['001', '010'],['010', '000'],['011', '100']]

So now you could add a new column identical to the last column like this: 因此,现在您可以添加一个与最后一列相同的新列,如下所示:

# Loop through all the rows
for row in data:
  lastColumn = row[-1]
  # Now add the new column to the current row
  row.append(lastColumn)

A list comprehension can do this quickly. 列表理解可以快速做到这一点。 This code doesn't perform the swap, but it looks like you have that working already. 这段代码不会执行交换,但是看起来您已经在工作。 :) :)

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.

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