比较Python中的两个列表A,B,查找A中与B中相同数字相对应的所有元素 [英] Compare two lists A, B in Python find all elements in A which correspond to the same number in B

查看:1290
本文介绍了比较Python中的两个列表A,B,查找A中与B中相同数字相对应的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个Python列表"A"和"B",以便可以找到 A中的所有元素,它们对应于B中的相同数字.我想对 B中的每个数字执行此操作.例如,如果

I want to compare two Python lists, 'A' and 'B' in such a manner that I can find all elements in A which correspond to the same number in B. I want to do this for each number in B. For example, if

A = [5, 7, 9, 12, 8, 16, 25]
B = [2, 1, 3, 2, 3, 1, 4]

我想得到

[7,16] corresponding to the number 1 of listB
[5, 12] corresponding to the number 2 of listB
[9, 8] corresponding to the number 3 of listB
[25] corresponding to the number 4 of listB

A和B始终具有相同的长度.

A and B will always have the same lengths.

推荐答案

您可以使用

You can use zip to create tuples which consist from one element from both lists, then sort them and finally group them by value from B:

>>> from itertools import groupby
>>> A = [5, 7, 9, 12, 8, 16, 25]
>>> B = [2, 1, 3, 2, 3, 1, 4]
>>> for k, g in groupby(sorted(zip(B,A)), key=lambda x: x[0]):
...     print('{} corresponds to {}'.format([x[1] for x in g], k))
... 
[7, 16] corresponds to 1
[5, 12] corresponds to 2
[8, 9] corresponds to 3
[25] corresponds to 4

在上面的zip(B, A)中返回可重复的元组,其中每个元组都具有BA中的元素:

In above zip(B, A) returns iterable of tuples where each tuple has element from B and A:

>>> list(zip(B,A))
[(2, 5), (1, 7), (3, 9), (2, 12), (3, 8), (1, 16), (4, 25)]

然后对

上面的结果进行排序,以使所有来自B的具有相同值的元组彼此相邻:

Result of above is then sorted so that all the tuples with same value from B are next to each other:

>>> sorted(zip(B,A))
[(1, 7), (1, 16), (2, 5), (2, 12), (3, 8), (3, 9), (4, 25)]

排序结果传递给 groupby 它根据键函数返回的值对元组进行分组,在这种情况下,元组中的第一项.结果是(key, group)元组可迭代的,其中组是元素可迭代的:

Result of sorting is passed to groupby which groups the tuples based on value returned by key function, in this case the first item in the tuple. Result is iterable of (key, group) tuples where group is iterable of elements:

>>> [(k, list(g)) for k, g in groupby(sorted(zip(B,A)), key=lambda x: x[0])]
[(1, [(1, 7), (1, 16)]), (2, [(2, 5), (2, 12)]), (3, [(3, 8), (3, 9)]), (4, [(4, 25)])]

这篇关于比较Python中的两个列表A,B,查找A中与B中相同数字相对应的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆