Search code examples
pythonloopscoding-style

How to write this in an eaiser way?


How could I write this in an eaiser way?

product_pairs = 
 [[(1, 2), (1, 3), (1, 6), (1, 8), (1, 9), (2, 3), (2, 6), (2, 8), (2, 9), (3, 6), (3, 
   8), (3, 9), (6, 8), (6, 9), (8, 9)],
 [(0, 5), (0, 9), (5, 9)],
 [(0, 9)],
 [(0, 4), (0, 5), (0, 7), (0, 9), (4, 5), (4, 7), (4, 9), (5, 7), (5, 9), (7, 9)],
 [(3, 8)],
 [(1, 3), (1, 6), (1, 8), (3, 6), (3, 8), (6, 8)],
 [(0, 5), (0, 9), (5, 9)],
 [(3, 8)],
 [(0, 4), (0, 5), (0, 7), (4, 5), (4, 7), (5, 7)],
 [(0, 1), (0, 2), (0, 3), (0, 6), (1, 2), (1, 3), (1, 6), (2, 3), (2, 6), (3, 6)]]
cooccurences={} 
d={} 
pairs=[]
for lists in product_pairs: 
    for pair in lists: 
        if pair not in pairs: # If the pair is not in the dictionary
            pairs.append(pair) # Storing all the pairs in a list
            d[pair]=1 # Adding to the dictionary with value 1
        else: # If the pair is already in the dictionary
            d[pair]+=1 # Incrementing its value by 1
pairs.sort() # Sorting the pairs list

for pair in pairs: # Iterating through all pairs in sorted order
    cooccurences[pair]=d[pair] # Storing their value in a dictionary
print(cooccurences) # Displaying output

Output:

{(0, 1): 1, (0, 2): 1, (0, 3): 1, (0, 4): 2, (0, 5): 4, (0, 6): 1, (0, 7): 2, (0, 9): 4, (1, 2): 2, (1, 3): 3, (1, 6): 3, (1, 8): 2, (1, 9): 1, (2, 3): 2, (2, 6): 2, (2, 8): 1, (2, 9): 1, (3, 6): 3, (3, 8): 4, (3, 9): 1, (4, 5): 2, (4, 7): 2, (4, 9): 1, (5, 7): 2, (5, 9): 3, (6, 8): 2, (6, 9): 1, (7, 9): 1, (8, 9): 1}

Solution

  • Best done using collections.Counter (also take a look at collections.defaultdict for a slightly more "manual" approach):

    from collections import Counter
    
    counter = Counter(pair for product_list in product_pairs for pair in product_list)
    print(dict(counter.most_common()))