If a
and b
were lists of objects, each with a name property (e.g. a1 = A("1")
, b1 = B("1")
, etc.), how would I check for equivalency? I'm currently doing this:
如果a和b是对象列表,每个对象都有一个name属性(例如a1 = A(“1”),b1 = B(“1”)等),我该如何检查是否等效?我目前正在这样做:
aList = [ a1, a2, a3, a4, a5 ]
bList = [ b1, b2 ]
aNameList = []
bNameList = []
for i in aList:
aNameList.append( i.name )
for i in bList:
bNameList.append( i.name )
match = set(aNameList) & set(bNameList)
>>> set(['1', '2'])
But it seems kind of long and unnecessary. What is a better way to do this?
但它似乎有点长而且没必要。有什么更好的方法呢?
3 个解决方案
#1
4
You can use list comprehensions instead to replace those temporary lists and for-loops of your example:
您可以使用列表推导来替换示例的临时列表和for循环:
match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )
#2
0
The operator.attrgetter function was designed for extracting fields of interest:
operator.attrgetter函数用于提取感兴趣的字段:
set(map(attrgetter('name'), aList)) & set(map(attrgetter('name'), bList))
#3
0
you can replace the list comprehension (replacing the temporary lists and for loop) with map like:
您可以使用以下地图替换列表推导(替换临时列表和for循环):
name = lambda: n: n[name]
match = set(map(name,aList))&set(map(name,bList))
#1
4
You can use list comprehensions instead to replace those temporary lists and for-loops of your example:
您可以使用列表推导来替换示例的临时列表和for循环:
match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )
#2
0
The operator.attrgetter function was designed for extracting fields of interest:
operator.attrgetter函数用于提取感兴趣的字段:
set(map(attrgetter('name'), aList)) & set(map(attrgetter('name'), bList))
#3
0
you can replace the list comprehension (replacing the temporary lists and for loop) with map like:
您可以使用以下地图替换列表推导(替换临时列表和for循环):
name = lambda: n: n[name]
match = set(map(name,aList))&set(map(name,bList))