设置差异并丢弃顺序

发布于 2025-01-10 05:53:25 字数 392 浏览 0 评论 0原文

我有以下集合:

>>> s2 = set(((1,3),(2,3,6,4)))
>>> s1 = set(((1,3),(2,3,4,6)))
>>> s1.symmetric_difference(s2)
{(2, 3, 4, 6), (2, 3, 6, 4)}

我想比较上面的两个集合,但设置丢弃它们的顺序,这意味着它返回空集,例如:

>>> s1.symmetric_difference(s2)
set()

更新:

事实上,当两个集合的序列不同时,我想集合假设它们是一组。 我如何用Python中的集合来定义它?

I have the following sets:

>>> s2 = set(((1,3),(2,3,6,4)))
>>> s1 = set(((1,3),(2,3,4,6)))
>>> s1.symmetric_difference(s2)
{(2, 3, 4, 6), (2, 3, 6, 4)}

I want to compare two above sets but set discards order of them, It means It return null set such as:

>>> s1.symmetric_difference(s2)
set()

UPDATE:

Indeed when sequence of two sets are difference, I want to sets supposes they are one set.
How can I define it with sets in python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巷雨优美回忆 2025-01-17 05:53:25

将集合存储为集合而不是元组。由于您需要它们可散列,因此请使用冻结集。就像 frozenset((1,3)) 而不是 (1,3) 一样。

顺便说一句,您还可以使用 s1 ^ s2 获得对称差。

Store your sets not as tuples but as sets. Since you need them hashable, use frozensets. Like frozenset((1,3)) instead of (1,3).

Btw you can also get the symmetric difference with s1 ^ s2.

漫雪独思 2025-01-17 05:53:25

使顺序无关的一种方法是使其相同。您可以在将元组放入集合之前对其进行排序:

>>> s2 = set(tuple(sorted(s)) for s in (((1,3),(2,3,6,4))))
>>> s1 = set(tuple(sorted(s)) for s in (((1,3),(2,3,4,6))))
>>> s1.symmetric_difference(s2)
set()

One way to make order irrelevant is to make it the same. You could sort the tuples prior to putting them in a set:

>>> s2 = set(tuple(sorted(s)) for s in (((1,3),(2,3,6,4))))
>>> s1 = set(tuple(sorted(s)) for s in (((1,3),(2,3,4,6))))
>>> s1.symmetric_difference(s2)
set()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文