[英]Intersection of Object Attributes in Python
因此,我制作了2套这样的对象。
class 4digits:
def __init__(self, value):
self.value = value
self.first = (value - (value % 100)) / 100
self.last = value % 100
这些都是4位数字的对象,所以就像...
object.value = 1234
object.first = 12
object.last = 34
如果我有两个set1和set2,我想将set1和set2更新为仅包含set1具有与set2的第一个属性匹配的最后一个属性的对象。
例如... set1中的1234将匹配set 2中的3456。
我可以很容易地将其作为列表而不是集合来进行操作,但是如果我能弄清楚该过程,但不确定如何返回对象属性的交集,则集合的效率会大大提高。 任何帮助。
编辑:因为我被要求输入代码,而我的假设与我实际所做的并不完全相同。
感谢Jez,我得到了以下答案:
def lastinfirst(list1, list2):
firsts = set( l2.first for l2 in list2)
newlist1 = [ l1 for l1 in list1 if l1.last in firsts]
return newlist1
def firstinlast(list1, list2):
lasts = set( l1.last for l1 in list1)
newlist2 = [ l2 for l2 in list2 if l2.first in lasts]
return newlist2
如果我已正确理解您想要的内容,则应该这样做:
# Get the set of unique boroughs in which people want rooms:
wantedboroughs = set( w.borough for w in wantrooms )
# Get all records for people who have rooms in those boroughs:
result = [ h for h in haverooms if h.borough in wantedboroughs ]
好吧,现在您已编辑问题,根本不涉及房间和行政区。 但是也许您可以概括一下此处示例的原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.