简体   繁体   中英

create list based on values in two other lists

Suppose that I have two lists that look like this:

A = [(1,4), (5,2), (10, 8), (11, 3), (59, 14)]
B = [4, 2, 3, 4, 8, 14, 4, 2]

I want to create a new list called C based on list A and list B so that C looks like this:

C = [(1,4), (5,2), (11,3), (1,4), (10,8), (59,14), (1,4), (5,2)]

That is, I want to link each value in B with the first value in the corresponding tuple in A based on the second value in the tuple.

I think I can do this with a for loop as follows:

C  = []
    for tuple in A:
        for number in B:
            if number == tuple[1]:
                C.append(tuple)

but I don't think this will be very efficient for large lists.

Question: Is there a more efficient way of creating list C ?

Thanks!

You can do the following:

A = [(1,4), (5,2), (10, 8), (11, 3), (59, 14)]
B = [4, 2, 3, 4, 8, 14, 4, 2]

a = {t[1]: t for t in reversed(A)}  # reverse to guarantee first tuple for each key
# {14: (59, 14), 3: (11, 3), 8: (10, 8), 2: (5, 2), 4: (1, 4)}

C = [a[x] for x in B]
#[(1, 4), (5, 2), (11, 3), (1, 4), (10, 8), (59, 14), (1, 4), (5, 2)]

You build a mapping from second values to first tuple in A and use that in the comprehension. This ensures you iterate both A and B only once.

You can use a dict to map the second item in the tuple to the first, and then use the mapping to create C :

d = {b: a for a, b in A}
C = [(d[k], k) for k in B]

C would become:

[(1, 4), (5, 2), (11, 3), (1, 4), (10, 8), (59, 14), (1, 4), (5, 2)]

You should first create a dictionary of the first Array of tuple with key as the second value and value as the tuple. This is have O(N) time complexity. Now when you are looping it on the second array of numbers, then you can access dictionary with O(1) time complexity. So the total time complexity of the whole program would be O(N) + O(M) where N is the length of tuple, and M is length of the array

A = [(1,4), (5,2), (10, 8), (11, 3), (59, 14)]
B = [4, 2, 3, 4, 8, 14, 4, 2]

X = {}
for element in A:
    X[element[1]] = element

# X = {4: (1, 4), 2: (5, 2), 8: (10, 8), 3: (11, 3), 14: (59, 14)}
C = []
for element in B:
    C.append(X[element])

print(C)
# [(1, 4), (5, 2), (11, 3), (1, 4), (10, 8), (59, 14), (1, 4), (5, 2)]

Using list comprehension

C = [(*[j[0] for j in A if j[1] == i], i) for i in B] 
# [(1, 4), (5, 2), (11, 3), (1, 4), (10, 8), (59, 14), (1, 4), (5, 2)]

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