【问题标题】:Add column to 2D array in Python在Python中将列添加到二维数组
【发布时间】:2017-01-16 21:38:21
【问题描述】:

我正在尝试在 Python 中向二维数组添加一个额外的列,但我被卡住了。我有一个如下所示的二维数组:

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

然后我从第 2 列交换 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

有什么想法吗?

【问题讨论】:

  • 它们是 numpy 数组还是列表?您的数据不是有效的 Python 语法。

标签: python arrays concatenation


【解决方案1】:

由于您将 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)

【讨论】:

    【解决方案2】:

    列表推导可以快速做到这一点。此代码不执行交换,但看起来您已经可以使用它了。 :)

    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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 2019-07-23
      • 2021-04-21
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      相关资源
      最近更新 更多