[英]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: 这利用了以下事实:
for i in s: print(i)
would print each character, seperately. for i in s: print(i)
将分别打印每个字符。 .get(key[,default])
1 that can take an option argument for "return this value if the key doesn't exist. .get(key[,default])
1可以使用一个选项参数表示“如果键不存在,则返回此值。 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.