我想比较两个Python列表,’A’和’B’,我可以找到A中所有与B中相同数字对应的元素.我想对B中的每个数字执行此操作.例如,如果
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将始终具有相同的长度.
解决方法:
您可以使用zip创建元组,这些元组由两个列表中的一个元素组成,然后对它们进行排序,最后按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)中返回可迭代的元组,其中每个元组都有来自B和A的元素:
>>> list(zip(B,A))
[(2, 5), (1, 7), (3, 9), (2, 12), (3, 8), (1, 16), (4, 25)]
然后对上面的结果进行排序,使得来自B的具有相同值的所有元组彼此相邻:
>>> sorted(zip(B,A))
[(1, 7), (1, 16), (2, 5), (2, 12), (3, 8), (3, 9), (4, 25)]
排序结果传递给groupby,它根据key函数返回的值对元组进行分组,在本例中是元组中的第一项.结果是(key,group)元组的可迭代元素,其中group是元素的可迭代元素:
>>> [(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,list
来源: https://codeday.me/bug/20190713/1453207.html