简体   繁体   English

根据另外两个列表中的值创建列表

[英]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: 我想基于列表A和列表B创建一个名为C的新列表,以便C看起来像这样:

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. 即,我想每个值在链接B与所述第一值中的相应元组中A基于在元组中的第二个值。

I think I can do this with a for loop as follows: 我想我可以使用for循环执行此操作,如下所示:

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 ? 问题:是否有更有效的方法来创建列表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. 您在A构建从第二个值到第一个tuple的映射,并在理解中使用它。 This ensures you iterate both A and B only once. 这可确保您只对AB一次迭代。

You can use a dict to map the second item in the tuple to the first, and then use the mapping to create C : 您可以使用dict将元组中的第二项映射到第一项,然后使用映射创建C

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

C would become: C将成为:

[(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. 您应该首先创建第一个元组数组的字典,其中key作为第二个值,值作为元组。 This is have O(N) time complexity. 这具有O(N)时间复杂度。 Now when you are looping it on the second array of numbers, then you can access dictionary with O(1) time complexity. 现在,当您在第二个数字数组上循环它时,您可以访问具有O(1)时间复杂度的字典。 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 所以整个程序的总时间复杂度为O(N) + O(M) ,其中N是元组的长度,M是数组的长度

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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