使用字典在python列表理解中的if-else

时间:2019-04-25 12:38:19

标签: python list dictionary list-comprehension

我正在尝试从紧缩字典中替换一个词。但是,当收缩字典中不存在该词但列表中确实存在该词时,我想返回该词。

当前,如果列表中的单词在词典中不存在,我的实现将会失败。

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

3 个答案:

答案 0 :(得分:4)

如果单词存在于字典中,则使用键中的值,否则使用dict.get(key,default_value)

使用单词本身

contractions.get(word,word)word获取密钥contractions的值(如果存在密钥),否则它会使用单词本身。

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

如果您希望if处于正确的位置,则可以使用

 "INSERT INTO customer(fname, lname, email, phone, country, dob, city, postal, address1, address2, password, regDate, status) "
        + "VALUES ('"+escape( customer.getFname() )+"', '"
                 +escape( customer.getLname() ) +"', '"
                 +escape( customer.getEmail() ) +"', '"
                 +escape( customer.getPhone() ) +"', '"
                 +escape( customer.getCountry() )+"',"
                     +"'"+customer.getDob() +"', '"
                     +escape( customer.getCity() ) +"', '"
                     +escape( customer.getPostal() ) +"', '"
                     +escape( customer.getAddress1() ) +"', '"
                     +escape( customer.getAddress2()) +"',"
                    + "'"+escape( customer.getPassword() )+"', NOW(), 'active' )";


public static String escape(String val) {
    return (val==null?null:val.replaceAll("'", "''"));
}

但是字典也有方便的方法

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)