如何使用集合理解在另一个集合中找到单个元素
我有两个集合,set1和set2 ...除了一个元素外,这两个集合中的几乎所有元素都是相同的。
支持代码如下:
set1 = {'dog', 'cat', 'turtle', 'monkey'}
set2 = {'dog', 'cat', 'turtle', 'gorilla'}
我试图使用SET理解将每个集合的唯一元素放入其自己的变量中。
set1Unique = 'monkey'
set2Unique = 'gorilla'
我已经通过以下内容来正常工作,但是使用集合理解不是必需的。
set1UniqueElements = set1 - set2
set1Unique = list(set1UniqueElements)[0]
I have two sets, set1 and set2... Almost all elements in both sets are the same except for one element.
Supporting code is below:
set1 = {'dog', 'cat', 'turtle', 'monkey'}
set2 = {'dog', 'cat', 'turtle', 'gorilla'}
I am trying to get the unique element of each set into its own variable using set comprehension.
set1Unique = 'monkey'
set2Unique = 'gorilla'
I have got it working by doing the following but it is not what is required, using set comprehension is.
set1UniqueElements = set1 - set2
set1Unique = list(set1UniqueElements)[0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
唯一项目是集合中不在另一组中的元素。因此:
要从集合中获取任意元素(将单元素集转换为单个元素),您可以使用
set.pop()
:The unique item is the element in the set that's not in the other set. Hence:
To get an arbitrary element from the set (converting a single-element set to that single element on its own) you can use
set.pop()
:如果您保证了SET2中至少有一个不在SET1中的元素,而您只是在寻找第一个元素:
此代码在
set2
中找到任何元素后立即停止。不在set1
中。If you are guaranteed that there is at least one element in set2 that is not in set1, and you're only looking for the first such element:
This code stops as soon as it find any element in
set2
not inset1
.由于只有一个独特的元素,因此可以使用包装直接访问元素:
Since there is only a single unique element, it is possible to use packing to access the elements directly:
我会使用此方法:
您可以在Setnunique公式中计算EX。它节省了一条线,但是您要两次计算EX。
I would use this:
You can can compute ex inside the setNunique formulas. It saves a line, but you compute ex twice.