将列表中的数字分类到不同的集合中,并计算出现次数



我有一个数字列表,比如A = [9,10,16,19]

我有四套{8, 9, 10}, {11, 12, 13}, {14, 15, 16}, {17, 18, 19, 20}

对于列表A中的每个元素,将元素分类到给定的集合中,并计算每个集合对应的出现次数。

考虑到我给出的例子,输出应该是[2,0,1,1]

最好的方法是什么??

我使用了setset.intersection()方法:

# Sets are generated with curly brackets
# or the set() constructor
mysets = [{8,9,10} , {11,12,13} , {14,15,16}, {17,18,19,20}]
# A is a list, which is a very different datatype
# For this problem here, it wouldn't make a difference if A
# were a set as well
A =  [9,10,16,19]
[len(s.intersection(A)) for s in mysets]
>> [2, 0, 1, 1]
s0,s1,s2,s3 = [8,9,10] , [11,12,13] ,[14,15,16], [17,18,19,20]
sets = [s0,s1,s2,s3] #(these aren't sets, but ok) 
A= [9,12,16,19]
numbers = []
for s in sets:
n = sum(1 for x in s if x in A)
numbers.append(n)    
# numbers[i] is the number of shared elements between A and sets[i]
# you should consider extension to duplicate elements. 
# as written this may not give you the result you want on duplicate elements 

就像一行代码读取一样

numbers = [sum(1 for x in s if x in A) for s in sets]

仔细考虑您想对重复元素做什么。您可能需要修改此

最新更新