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

时间:2018-07-27 18:38:12

标签: python set

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

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

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

考虑我给出的示例,输出应该为[2,0,1,1]

执行此操作的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

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]

请仔细考虑要对重复元素执行的操作。您可能需要修改

答案 1 :(得分:2)

我使用了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]