列出对集合元组的理解



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

>>> 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保持不变!

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

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

最新更新