简体   繁体   English

如何在Python中为字典中的每个字符串索引匹配键获取值

[英]How to get value for each string index matching key in dictionary in Python

str = 'strings' str ='字符串'

new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 } new_D = {'r':1,'s':1,'t':1,'r':3,'i':4}

How can I get each letter in the string assigned to the value in the dictionary by match 'letter-key' and then summarize the values? 如何通过匹配“字母键”获得分配给字典中值的字符串中的每个字母,然后汇总值?

Thanks 谢谢

s = 'strings' #Don't name a variable str, that shadows the builtin str

new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }

sum_of_chars = sum([newD.get(k,0) for k in s]) #assuming 0 as default for "not in dictionary"

This takes advantage of the fact that: 这利用了以下事实:

  1. Strings are iterable. 字符串是可迭代的。 for i in s: print(i) would print each character, seperately. for i in s: print(i)将分别打印每个字符。
  2. Dictionaries have a .get(key[,default]) 1 that can take an option argument for "return this value if the key doesn't exist. 字典的.get(key[,default]) 1可以使用一个选项参数表示“如果键不存在,则返回此值。
  3. I'm using the built-in sum on a list comprehension for the sake of brevity. 为了简洁起见,我在列表理解中使用了内置sum Brevity can both be a virtue or a vice, but, hey, one list comp is still usually pretty readable after you know what they are. 简洁可以是一种美德,也可以是一种恶习,但是,嘿,一个列表组合通常在您知道它们是什么之后仍然很容易阅读。
string = 'strings'

new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }

sum_of_chars = 0
for character in string:
    if character in new_D:
        sum_of_chars += new_D[character]
    else:
        sum_of_chars += 1 # Default?

print(sum_of_chars)

btw, you should not use the name str because it shadows the builtin str and there's a mistake in your dictionary. 顺便说一句,您不应使用名称str,因为它会掩盖内置的str,并且词典中存在错误。 It contains the entry r two times which doesn't make sense. 它包含两次入口r,这没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM