[英]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.