设置差异并丢弃顺序
我有以下集合:
>>> 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将集合存储为集合而不是元组。由于您需要它们可散列,因此请使用冻结集。就像
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
.使顺序无关的一种方法是使其相同。您可以在将元组放入集合之前对其进行排序:
One way to make order irrelevant is to make it the same. You could sort the tuples prior to putting them in a set: