python比较两个列表中不同的数、保存在,比较Python中的两个列表A,B,查找A中与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]

I would like to get

[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 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

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值