What would be the best way to do the following case-insensitive intersection:

a1 = ['Disney', 'Fox']
a2 = ['paramount', 'fox']
a1.intersection(a2)
> ['fox']

通常我会做一个列表理解,将两者转换为所有小写:
>>> set([_.lower() for _ in a1]).intersection(set([_.lower() for _ in a2]))
set(['fox'])

但有点难看。有更好的办法吗?

最佳答案

Using the set comprehension syntax is slightly less ugly:

>>> {str.casefold(x) for x in a1} & {str.casefold(x) for x in a2}
{'fox'}

算法是相同的,并且没有任何更有效的方法可用,因为字符串的散列值区分大小写。

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

10-08 22:02