Python - 在这种情况下如何解释将数据分配给数组

时间:2017-05-20 12:49:42

标签: python arrays

请参阅下面的代码,为什么要这样做

array[0][0] = 'Tadaaaa'

更改了5个元素而不是1个元素?

首先,创建一个空数组:

x, y = 5, 3

# when you multiply it's copying, so the ids of each item is the same
array = [[set()] * y] * x
array

我会得到:

[[set(), set(), set()],
 [set(), set(), set()],
 [set(), set(), set()],
 [set(), set(), set()],
 [set(), set(), set()]]

然后为元素赋值:

array[3][2].add('BBC')
array

我会得到:

[[{'BBC'}, {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}]]

但是当我这样做时:

array[0][0] = 'Tadaaaa'
array

我明白了:

[['Tadaaaa', {'BBC'}, {'BBC'}],
 ['Tadaaaa', {'BBC'}, {'BBC'}],
 ['Tadaaaa', {'BBC'}, {'BBC'}],
 ['Tadaaaa', {'BBC'}, {'BBC'}],
 ['Tadaaaa', {'BBC'}, {'BBC'}]]

这里发生了什么?

我以为我会得到这样的东西:

[['Tadaaaa', {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}],
 [{'BBC'}, {'BBC'}, {'BBC'}]]

2 个答案:

答案 0 :(得分:5)

首先,这些不是数组;他们是名单。

其次,使用*创建一个对相同 set对象的引用列表,而不是对不同set个对象的引用列表。

>>> x = [set()]*3
>>> id(x[0]), id(x[1]), id(x[2])
(4297985280, 4297985280, 4297985280)

相反,使用列表推导来确保每个元素调用一次set()

>>> x = [set() for _ in range(3)]
>>> id(x[0]), id(x[1]), id(x[2])
(4298169136, 4298363424, 4298363656)

您可以使用嵌套列表推导来获取所需的嵌套列表:

>>> x, y = 5, 3
>>> array = [[set() for _ in range(y)] for _ in range(x)]
>>> for x in array:
...   map(id, x)
...
[4298169136, 4298363424, 4298363656]
[4297985280, 4298363888, 4298364120]
[4298364352, 4298364584, 4298364816]
[4298365048, 4298365280, 4298365512]
[4298365744, 4298365976, 4298366208]

如您所见,数组中的每个元素都是一个不同的set对象。

答案 1 :(得分:0)

这是duplicate question,你通过放置:

重复相同的元素(空集)
array = [[set()] * y] * x

您需要使用for循环将阵列初始化为一个解决方案 这就是全部