【问题标题】:Making a row into a column [duplicate]将一行变成一列[重复]
【发布时间】:2020-01-22 01:25:11
【问题描述】:

我正在尝试将一行变成一列。也就是说,我有row = [2, 4, 8],我需要[[2], [4], [8]]。 所以我做了这个代码:

row = [2, 4, 8]
column = [[]] * 3
for y in range(3):
    column[y].append(row[y])

column 在第一个循环之后必须是 [[2], [], []]。但它是[[2], [2], [2]]。有谁知道怎么回事?

【问题讨论】:

标签: python arrays python-3.x list matrix


【解决方案1】:
#see if this soves your issue
row = [2, 4, 8]
col=[]
for i in row:
    col.append([i])

【讨论】:

    【解决方案2】:

    试试这个:

    raw = [2, 4, 8]
    column =[]
    
    for case in raw:
        column.append([case])
    

    关于你的问题,应该是因为一个列表包含一个值和下一次迭代的内存。

    a = [1]
    b = a
    b[0] = 2
    print(a)  # return [2]
    

    【讨论】:

    • 其实在我的真实代码中,for循环是在另一个循环里面,列是在循环外面定义的。我需要board = [[2, a1, b1], [4, a2, b2], [8, a3, b3]]
    【解决方案3】:

    你可以使用:

    column = [[i] for i in row]
    

    根据以下成绩单:

    Python 3.6.5 (default, Apr  1 2018, 05:46:30)
    [GCC 7.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> row = [2, 4, 8]
    >>> column = [[i] for i in row]
    >>> print(column)
    [[2], [4], [8]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2019-08-18
      相关资源
      最近更新 更多