gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:40:17 24 4
gpt4 key购买 nike

我有两套(虽然我可以做列表,或其他):

a = frozenset(('Today','I','am','fine'))
b = frozenset(('hello','how','are','you','today'))

我想得到:

frozenset(['Today'])

或至少:

frozenset(['today'])

如果我将我认为的所有内容都小写,则第二个选项是可行的,但我正在寻找一种更优雅的方式。是否可以做

a.intersection(b) 

以不区分大小写的方式?

Django 中的快捷方式也很好,因为我正在使用该框架。

下面的交集方法示例(我不知道如何在评论中设置此格式):

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

最佳答案

这是适用于任何一对可迭代对象的版本:

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]

例子:

print intersection('Today I am fine'.split(),
'Hello How a re you TODAY'.split(),
key=str.lower)
# -> [(['Today'], ['TODAY'])]

关于python - Python 中不区分大小写的集合比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1479979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com