[英]Access python dictionary with case insensitive string
我正在努力查看是否存在一种方法来访问 python 字典,其中字符串作为具有正确字符串但不区分大小写的键
例如使用此代码:
dictionary = {'one': 1, 'two': 2, 'three', 3}
list = ['One', 'second', 'THree']
for item in list:
if item in dictionary:
print(item)
我无法找到输出为:'One THree' 的方法,即。 比较字典的键和我不区分大小写的字符串
有没有办法做到这一点?
您需要通过将dictionary.keys()
转换为小写或将list
元素转换为小写或两者都将大小写转换为小写来处理不区分大小写的问题:
for item in list:
if item.lower() in map(str.lower, dictionary.keys()):
print(item)
您可以使用lower()
或upper()
,但在这两种情况下都必须保持一致。
创建一个小写字典键列表,然后将列表中每个项目的小写变体与此列表进行比较。
dictionary = {'one': 1, 'two': 2, 'three': 3}
list = ['One', 'second', 'THree']
for item in list:
if item.lower() in [key.lower() for key in dictionary.keys()]:
print(item)
因此:
One
THree
使用字符串方法lower
:
dictionary = {'one': 1, 'two': 2, 'three': 3}
list = ['One', 'second', 'THree']
for item in list:
if item.lower() in dictionary:
print(item)
输出:
One
THree
尝试这个:
dictionary = {'one': 1, 'two': 2, 'three': 3}
list = ['One', 'second', 'THree']
for item in list:
if item.lower() in [d.lower() for d in dictionary.keys()]:
print(item)
使用casefold()
进行不区分大小写的搜索:
dictionary = {'one': 1, 'two': 2, 'three': 3}
list = ['One', 'second', 'THree']
for item in list:
if item.casefold() in dictionary:
print(item)
列表理解方式:
print( '\n'.join([item for item in list if item.casefold() in dictionary]))
尝试使用 python lambda
关键字:
l = ['One', 'second', 'THree']
lc = lambda x: [i for i in x if i.lower() in dictionary]
print(lc(l))
输出:
['One', 'THree']
注意:我将变量名list
更改为l
因为 list 是一个 python 关键字,所以如果你想调用 list 关键字,它不会调用 list 关键字,而是调用列表
正确的做法是使用casefold函数。 此函数可从 Python 3.3 获得。
返回字符串的 casefolded 副本。 大小写折叠字符串可用于无大小写匹配。
Casefolding 类似于小写,但更具侵略性,因为它旨在消除字符串中的所有大小写区别。 例如,德语小写字母“ß”相当于“ss”。 由于它已经是小写的,lower() 对 'ß' 没有任何作用; casefold() 将其转换为“ss”。
casefolding 算法在 Unicode 标准的第 3.13 节中描述。
dictionary = {"one": 1, "two": 2, "three": 3}
list = ["One", "second", "THree"]
print(*(item for item in list if item.casefold() in dictionary), sep="\n")
输出:
One
THree
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.