简体   繁体   中英

Creating a dictionary given values from a list and dictionary

So, I am given a list

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]]]

and a dictionary d.

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

For the output, I want a dictionary:

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

This output is formed by passing through each sublist of a and checking the number of times each element appears in d. Let's look at index 0 of a. Now we look at a[0][0]and
a[0][1] and since 0 appears twice in both and 3 appears 4 times (comparing it to d), [0,3] are added to index 0. Similarly, at index 1, 0 appears just once and is not added to the dictionary at index 1.

What I tried so far:

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)

Edit: A version that work

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)

output:

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

The try except block is merely for convenience, If you insist you can if your way around this by checking if a key is in all counters (which is a requirement for it to be add)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM