列出对集合元组的理解

时间:2016-05-15 16:34:19

标签: python set list-comprehension python-3.5

有人可以解释一下发生了什么吗?

>>> xx = ({1,2}, {2,3}, {3,4}, {4,2})
>>> yy = [x.discard(2) for x in xx]
>>> yy
[None, None, None, None]
>>> xx
({1}, {3}, {3, 4}, {4})
>>> id(xx)
4315823704
>>> id(yy)
4315797064

我希望yy等于[{1}, {3}, {3, 4}, {4}]xx保持不变!

1 个答案:

答案 0 :(得分:1)

要获得所需的结果,您可以使用表单的列表理解:

yy = [x - {2} for x in xx]

例如:

>>> xx = ({1,2}, {2,3}, {3,4}, {4,2})
>>> yy = [x - {2} for x in xx]
>>> yy
[{1}, {3}, {3, 4}, {4}]
>>> xx
({1, 2}, {2, 3}, {3, 4}, {2, 4})

您的原始示例表现如下:

>>> xx = ({1,2}, {2,3}, {3,4}, {4,2})
>>> yy = []
>>> for x in xx:
...   # Here, x is a reference to one of the existing sets in xx.
...   # x.discard modifies x in place and returns None.
...   y = x.discard(2)
...   # y is None at this point.
...   yy.append(y)
...
>>> yy
[None, None, None, None]
>>> xx
({1}, {3}, {3, 4}, {4})