python3 比较列表,如何比较两个列表中的项目Python 3.3

I tried using cmp(list1, list2) to learn it's no longer supported in Python 3.3. I've tried many other complex approaches, but none have worked.

I have two lists of which both contain just words and I want it to check to see how many words feature in both and return the number for how many.

解决方案

You can find the length of the set intersection using & like this:

len(set(list1) & set(list2))

Example:

>>>len(set(['cat','dog','pup']) & set(['rat','cat','wolf']))

1

>>>set(['cat','dog','pup']) & set(['rat','cat','wolf'])

{'cat'}

Alternatively, if you don't want to use sets for some reason, you can always use collections.Counter, which supports most multiset operations:

>>> from collections import Counter

>>> print(list((Counter(['cat','dog','wolf']) & Counter(['pig','fish','cat'])).elements()))

['cat']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值