如果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'])但它似乎有点长而且没必要。 有什么更好的方法呢?
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:
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?
最满意答案
您可以使用列表推导来替换示例的临时列表和for循环:
match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )You can use list comprehensions instead to replace those temporary lists and for-loops of your example:
match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )在两个数组中获取匹配元素的值(Get matching elements' values in two arrays)如果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'])但它似乎有点长而且没必要。 有什么更好的方法呢?
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:
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?
最满意答案
您可以使用列表推导来替换示例的临时列表和for循环:
match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )You can use list comprehensions instead to replace those temporary lists and for-loops of your example:
match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )
发布评论