查找列表中各个组的出现次数

时间:2019-06-20 10:25:10

标签: python-3.x

`所以,我得到一个清单-

group = [2,1,3,4]

此列表的每个索引代表一个组。 所以group 0 = 2

group 1 = 1
group 2 = 3 
group 3 = 4

我还得到另一个列表:

l =[[[0, 0, 3, 3, 3, 3], [0, 0, 1, 3, 3, 3, 3]], [[0, 1]], [[2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3]], [[0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3]]]

我想要的输出是:

dict = {0:[0,3],1;[1],2:[2,3],3:[0,2]}

如果元素出现在l的每个子列表中的次数,即l [0] [0]和l [0] [1]都出现0次,则将其添加到字典的索引0 。由于l[0][0]l[0][1]都有3次出现4次(这是因为group [3]为4),因此将其添加到索引0。 现在在l[1][0]中出现,并且0仅出现一次(而不是两次),因此不会将其添加到索引1。但是1只会出现一次,因此将其添加到索引1。谢谢!

到目前为止,我已经尝试过:

def tryin(l,groups):
    for i in range(len(l)):
        count = 0
        for j in range(len(l[i])):
            if j in (l[i][j]):
                count+=1
                if count == groups[i]:
                    print(i,j)

1 个答案:

答案 0 :(得分:0)

尝试此代码:

输入:

group = [2,1,3,4]
l =[[[0, 0, 3, 3, 3, 3], [0, 0, 1, 3, 3, 3, 3]], [[0, 1]], [[2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3], [2, 2, 2, 3, 3, 3, 3]], [[0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3], [0, 0, 2, 2, 2, 3, 3, 3, 3]]]



def IntersecOfSets(list_):
    result = set(list_[0])
    for s in list_[1:]:
        result.intersection_update(s)

        return result
def nb_occ(l,group):
    d = {}
    for i in l:
        l2=[]
        for j in i:
            l1 = []
            for x in group:

                if j.count(group.index(x)) >= x :
                    y=group.index(x)
                    l1.append(y)
            l2.append(l1)
        if len(l2)>1:
            d[str(l.index(i))]= IntersecOfSets(l2)
        else:
            d[str(l.index(i))]= l2[0]
    return d
print(nb_occ(l,group))

输出:

{'2': {2, 3}, '1': [1], '0': {0, 3}, '3': {0, 2}}