【问题标题】:Can I use update method of set in Python to merge two set (x-y) and (y-x)?我可以在 Python 中使用 set 的 update 方法来合并两个集合(x-y)和(y-x)吗?
【发布时间】: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),所以结果应该是一样的?

【问题讨论】:

标签: python python-3.x set symmetric-difference


【解决方案1】:

稍作改动即可:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x - y
z.update((y - x))

print(z)

{'google', 'cherry', 'microsoft', 'banana'}

更新操作是就地的,因此对于您使用的表达式x-y 最终会是就地更新的临时设置值。因此,分配最终是None

【讨论】:

  • 还有z = (x-y) | (y-x) of z = (x-y).union(y-x)
【解决方案2】:

正如@MisterMiyagi 所说,更新功能到位操作。您可以将 (x - y) 保存在某个变量中,并且可以执行更新操作。像这样的。

var = (x - y)
var.update((y - x))

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 2013-02-26
    • 2022-11-30
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 2014-02-17
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多