为了账号安全,请及时绑定邮箱和手机立即绑定

如何向用户询问字典中的键,如果它在字典中,则显示值

如何向用户询问字典中的键,如果它在字典中,则显示值

Qyouu 2021-12-29 19:40:28
当用户输入键(整数)时如何在字典中显示键(整数)string = input("Please enter a name> ")def enumerate_string(string):  s = {}  for i,letter in enumerate(string):     s[i] = letterx = enumerate_string(string)string2 = input("enter several integers separated by a comma ")string3 = string2.split(',')if string3 in set(x):   print(x[string3])
查看完整描述

2 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

我正在更新您的部分代码:


string2 = input("enter several integers separated by a comma ") # 0,1,2

string3 = string2.split(',') # string3 is a list of numbers but as strings

# ['0','1','2']

string3=[int(num) for num in string3] # [0,1,2]

for num in string3:

   print(x.get(num))# will return the value corresponding to the key


查看完整回答
反对 回复 2021-12-29
?
DIEA

TA贡献1820条经验 获得超2个赞

使用这段代码,简单地做同样的事情,但在最后做一个循环,并return在函数中有一个:


string = input("Please enter a name> ")

def enumerate_string(string):

    s = {}

    for i,letter in enumerate(string):

        s[i] = letter

    return s


x = enumerate_string(string)

string2 = input("enter several integers separated by a comma ")

string3 = string2.split(',')

for i in string3:

    if int(i) in x:

        print(x[int(i)])

示例输出:


Please enter a name> John Doe

enter several integers separated by a comma 0,1,2

J

o

h


查看完整回答
反对 回复 2021-12-29
  • 2 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信