【问题标题】:Display value of the variables显示变量的值
【发布时间】:2019-03-15 04:32:53
【问题描述】:

代码:

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

【问题讨论】:

  • 那么你有一个字典还是一堆变量?选择一个并提出一个明确的问题。
  • 还有1个问题,如果我想找到值的总和,我可以使用sum()吗?

标签: python variables output


【解决方案1】:

一种通用的方法是借助 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))

这样就不需要字典了

【讨论】:

  • 不错。但是您也可以使用for letter in word: 来执行此操作,这样您就有了用户输入。还可以考虑使用 lower()
【解决方案2】:

由于score 是一个字典,您可以简单地使用x 作为索引来获取它的值:

for x in word:
  print(x, score[x])

【讨论】:

  • 还有1个问题,我怎样才能找到值的总和?
  • 那就是sum(score[x] for x in word)
【解决方案3】:

使用 python 3.6 f-strings 的单线器。

print("\n".join((f"{score} {scores[score]}" for score in scores))

或者如果你不能使用f-strings,你可以使用:

print(("\n".join("{} {}".format(score, scores[score]) for score in scores))

【讨论】:

  • 大声笑我只是在阅读我的答案,并在我的脑海中弹出“[score for score in Seven_years_ago]”。还有其他人吗?
【解决方案4】:

for 循环仅遍历键。要获得这些值,您还需要

for letter, value in score.items():
    print(...)

【讨论】:

  • 这不起作用。您忽略了用户输入,只打印了整个字典
猜你喜欢
  • 1970-01-01
  • 2011-04-19
  • 2016-04-03
  • 2022-01-23
  • 2019-09-10
  • 1970-01-01
  • 2021-04-05
  • 2011-03-31
  • 1970-01-01
相关资源
最近更新 更多