a = [1, 2, 9, 5, 1] b = [9, 8, 7, 6, 5]
我想计算两个列表之间重复的次数。因此,使用上述方法,我想返回2的计数,因为9和5在两个列表中都是相同的。
我尝试了类似的方法,但效果不佳。
def filter_(x, y): count = 0 for num in y: if num in x: count += 1 return count
更好,更短的方法:
>>> a = [1, 2, 9, 5, 1] >>> b = [9, 8, 7, 6, 5] >>> len(set(a) & set(b)) # & is intersection - elements common to both 2
为什么您的代码不起作用:
>>> def filter_(x, y): ... count = 0 ... for num in y: ... if num in x: ... count += 1 ... return count ... >>> filter_(a, b) 2
您return count在for循环内,返回时未完成执行。
return count