python集合比较大小_Python中的集合不区分大小写的比较

1586010002-jmsa.png

I have two sets (although I can do lists, or whatever):

a = frozenset(('Today','I','am','fine'))

b = frozenset(('hello','how','are','you','today'))

I want to get:

frozenset(['Today'])

or at least:

frozenset(['today'])

The second option is doable if I lowercase everything I presume, but I'm looking for a more elegant way. Is it possible to do

a.intersection(b)

in a case-insensitive manner?

Shortcuts in Django are also fine since I'm using that framework.

Example from intersection method below (I couldn't figure out how to get this formatted in a comment):

print intersection('Today I am fine tomorrow'.split(),

'Hello How a re you TODAY and today and Today and Tomorrow'.split(),

key=str.lower)

[(['tomorrow'], ['Tomorrow']), (['Today'], ['TODAY', 'today', 'Today'])]

解决方案

Here's version that works for any pair of iterables:

def intersection(iterableA, iterableB, key=lambda x: x):

"""Return the intersection of two iterables with respect to `key` function.

"""

def unify(iterable):

d = {}

for item in iterable:

d.setdefault(key(item), []).append(item)

return d

A, B = unify(iterableA), unify(iterableB)

return [(A[k], B[k]) for k in A if k in B]

Example:

print intersection('Today I am fine'.split(),

'Hello How a re you TODAY'.split(),

key=str.lower)

# -> [(['Today'], ['TODAY'])]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值