[英]if-else in a python list comprehension using dictionary
我正在嘗試替換收縮字典中的一個詞。 但是,當它在收縮字典中不存在但在列表中存在時,我想返回該詞。
目前,如果列表中的單詞在字典中不存在,我的實現將失敗。
contractions = {
"costumer": "customer",
"billl": "bill",
"acct": "account"}
abc = ['acct','costumer','abc']
[w.replace(w,contractions[w]) for w in abc if w in contractions else w for w in abc]
預期輸出: ['account','customer','abc']
如果單詞存在於字典中,則使用鍵中的值,否則使用dict.get(key,default_value)
使用單詞本身
contractions.get(word,word)
得到key的值word
從contractions
如果密鑰存在,否則它使用word`本身
contractions = {
"costumer": "customer",
"billl": "bill",
"acct": "account"}
abc = ['acct','costumer','abc']
res = [contractions.get(word,word) for word in abc]
print(res)
#['account', 'customer', 'abc']
contractions = {
"costumer": "customer",
"billl": "bill",
"acct": "account"}
abc = ['acct','costumer','abc']
[w.replace(w,contractions[w]) if w in contractions else w for w in abc ]
給你:
['account', 'customer', 'abc']
你可以用 if 當你在正確的位置上取悅 if
contractions = {
"costumer": "customer",
"billl": "bill",
"acct": "account"}
abc = ['acct','costumer','abc']
res=[contractions[w] if w in contractions else w for w in abc]
print(res)
但是 dict 也有一個方便的方法
res=[contractions.get(w,w) for w in abc]
print(res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.