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

当用户输入键(整数)时如何在字典中显示键(整数)


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

def enumerate_string(string):

  s = {}

  for i,letter in enumerate(string):

     s[i] = letter

x = enumerate_string(string)

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

string3 = string2.split(',')

if string3 in set(x):

   print(x[string3])


Qyouu
浏览 134回答 2
2回答

aluckdog

我正在更新您的部分代码:string2 = input("enter several integers separated by a comma ") # 0,1,2string3 = 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

DIEA

使用这段代码,简单地做同样的事情,但在最后做一个循环,并return在函数中有一个:string = input("Please enter a name> ")def enumerate_string(string):    s = {}    for i,letter in enumerate(string):        s[i] = letter    return sx = 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 Doeenter several integers separated by a comma 0,1,2Joh
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python