[英]Display value of the variables
码:
score={'a':1,'b':2,'c':3,'d':4,'e':5} #value of the alphabet
要么
a=1
b=2
c=3
d=4
e=5
word=input('Enter a word:')
word_list=list(word)
for x in word:
print(x)
如果我输入bad
输出:
b
a
d
问题:如何将字母的值放在它的旁边(在输出中),像这样:
b 2
a 1
d 4
一种通用的方法是借助ord函数,该函数代表字母的整数值
for letter in ['b', 'a', 'd']:
print(letter + ' ' + str(ord(letter) - ord('a') + 1))
要么
word = 'test'
for letter in word:
print(letter + ' ' + str(ord(letter) - ord('a') + 1))
这样就不需要字典
由于score
是字典,因此您可以简单地使用x
作为索引来获取其值:
for x in word:
print(x, score[x])
使用python 3.6 f-strings的 One-Liner。
print("\n".join((f"{score} {scores[score]}" for score in scores))
或者,如果您不能使用f-strings
,则可以使用:
print(("\n".join("{} {}".format(score, scores[score]) for score in scores))
for
循环仅迭代键。 要也获取值,您需要
for letter, value in score.items():
print(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.