问题描述
我有一个元素列表:
x = [1,3,5,7,9]
y = [2,4,6,8,0]
现在,我想执行一个操作,该操作为我提供了第三列表z中的元素存在"的列表:
Now I want to perform an operation which gives me the list in which "MOST OF" the elements in a third list z exist:
z = [2,3,5,7] #primes
我要这样做,以便返回z中具有"MOST OF"项的列表,而不是z中具有任何元素的列表.
I want to do it such that the list with "MOST OF" the items in z is returned,not the list with any element in z..
如果无法使用列表,则可以使用元组或集合了...
If it is not possible with lists, I am ready to work with tuples or sets as-well...
样本:
mostOf(z) -> x
因为x包含z中的大多数值
since x contains most of the values in z
推荐答案
使用集合,您可以查看相交的大小...
working with sets, you can look at the size of the intersection ...
zset = set(z)
if len(zset.intersection(x)) > len(zset.intersection(y)):
...
如果您有可迭代的列表要检查:
If you have an iterable of lists to check:
iterable = (x,y)
您可以从获得具有最大交点的迭代:
You can get the iterable with the biggest intersection from:
def cmp_key(lst):
itersect_size = len(zset.intersection(lst))
return intersect_size,-len(lst)
list_with_biggest_intersection = max(iterable,key = cmp_key)
这篇关于"MOST-OF"指的是"MOST-OF".在python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!