【发布时间】:2021-08-31 00:02:41
【问题描述】:
我有这两个源代码,不明白区别
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z) ## z now is {'google', 'cherry', 'microsoft', 'banana'}
和
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = (x - y).update((y - x))
print(z) ## z now is NoneType
为什么第二个代码不会与第一个代码一样?据我所知,(x-y) 会返回一个集合,然后我用 (y - x) 应用更新方法来合并 (x-y) 集合和 (y-x),所以结果应该是一样的?
【问题讨论】:
-
set.update是一个就地操作,如list.append。这些在 Python 中总是返回None。 -
我明白你的意思,非常感谢@MisterMiyagi
标签: python python-3.x set symmetric-difference