简体   繁体   中英

Python: Compare two lists and create a dictionary

In Python, I have a list of pairs ( A ) and a list of integers ( B ). A and B always have the same length . I want to know of a fast way of finding all the elements (pairs) of A that correspond to the same value in B (by comparison of indices of A and B) and then store the values in a dictionary ( C ) (the keys of the dictionary would correspond to elements of B). As an example, if

A = [(0, 0), (0, 1), (0, 3), (0, 6), (0, 7), (1, 3), (1, 7)]
B = [  2,      5,      5,       1,      5,     4,       1  ]

then

C = {1: [(0,6),(1,7)], 2: [(0,0)],  4: [(1,3)], 5[(0,1), (0,3), (0,7)]}

Presently, I am trying this approach:

C = {}
for a, b in zip(A, B):
    C.setdefault(b, [])
    C[b].append(a)

While this approach gives me the desired result, I would like some approach which will be way faster (since I need to work with big datasets). I will be thankful if anyone can suggest a fast way to implement this ( ie find the dictionary C once one is in knowledge of lists A and B).

I would have suggested

for i in range (0,len(B)):
    C2.setdefault(B[i], [])
    C2[B[i]].append(A[i])

it would save the zip (A,B) process

import collections
C = collections.defaultdict(list)
for ind, key in enumerate(B):
    C[key].append(A[ind])

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