【问题标题】:python: assign value to multiple dimensional listpython:为多维列表赋值
【发布时间】:2018-09-22 04:23:20
【问题描述】:

我有以下代码:

X = [[[None] * 4] * 2] * 6

for i in range(0, 6):
    X[i][0][0] = i

X

结果给出:

[[[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]]]

这对我来说很奇怪,结果不应该像下面这样吗?

[[[0, None, None, None], [0, None, None, None]],
 [[1, None, None, None], [1, None, None, None]],
 [[2, None, None, None], [2, None, None, None]],
 [[3, None, None, None], [3, None, None, None]],
 [[4, None, None, None], [4, None, None, None]],
 [[5, None, None, None], [5, None, None, None]]]

我在这里错过了什么?谢谢!

【问题讨论】:

  • 使用[[[[None] for i in range(4)] for j in range(2)] for k in range(6)] 创建您的列表。您只是在创建对同一个列表 atm 的引用。
  • 检查容器元素的id(),你会发现它们都是同一个列表。

标签: arrays python-2.7 list


【解决方案1】:
a = [[]] * 2  # here initiated a list and assigned to a.
id(a[0]) >>> 4509460384
id(a[1]) >>> 4509460384

b = [[] for _ in range(2)]  # here constructing a list and assigning to b.
id(b[0]) >>> 4509626808
id(b[1]) >>> 4509626880

希望这一切都解决了!

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多