根据列表和字典的值创建字典

时间:2019-06-26 19:25:57

标签: python

所以,我得到了一个清单

a =[[[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]]]

和字典d。

d = {0:2,1:1,2:3,3:4}

对于输出,我想要一本字典:

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

通过遍历a的每个子列表并检查每个元素在d中出现的次数来形成此输出。 让我们看一下a的索引0。现在我们来看一个[0] [0]和
a [0] [1]并且由于0都出现两次并且3出现了4次(将其与d进行比较),因此[0,3]被添加到索引0。类似地,在索引1处,0仅出现一次而并非已添加到索引为1的字典中。

到目前为止我尝试过的:

def example(a,d):
    for i in range(len(a)):
        count = 0
        for j in range(len(a[i])):
            if j in (a[i][j]):
                count+=1
                if count == d[i]:
                    print(i,j)

1 个答案:

答案 0 :(得分:0)

编辑:有效的版本

from collections import Counter
a = [[[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]]]
d = {0: 2, 1: 1, 2: 3, 3: 4}
output = {i: [] for i in range(len(a))}
for j, sublist in enumerate(a):
    counts = [Counter(i) for i in sublist]
    for k,v in d.items():
        try:
            if all(counts[i][k] == v for i in range(len(counts))):
                output[j].append(k)
        except: continue
print(output)

输出:

  

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

tryexcept块只是为了方便起见,如果您坚持可以通过检查所有计数器中是否都包含密钥(这是添加密钥的必要条件)来if来解决此问题