从带有变量的列表中调用对象

2024-04-20 13:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

list = [yes, no, seven]

print ("What do you want to pull from  the list?")
answer = input()

print (list[answer])

这种情况我该怎么办?我知道这个例子不起作用,但是如何使它起作用呢?你知道吗

编辑:我希望它是我输入的一个数字,0表示是,1表示否,2表示七如果可能的话


Tags: thetonoanswerfromyouinputdo
3条回答

首先,正确定义项目列表:

>>> items = ['yes', 'no', 'seven']

注意,我称之为items,因为^{}是一个内置函数。你知道吗

现在获取输入:

>>> answer = input("What do you want to pull from  the list? ")

此时,answer是一个字符串。但是项目列表中的索引需要一个数字,因此必须使用内置的^{}函数进行转换:

>>> index = int(answer)

现在可以在给定索引处打印项目:

>>> print(items[index])

你要找的是dict,不是list。你知道吗

my_dictionary = {'yes':1, 'no':4, 'seven':9}

answer = input("What do you want to pull from the dictionary? ")

print(my_dictionary[answer])
list_ = [yes, no, seven]

print ("What do you want to pull from  the list?")
answer = input()

print (list_[list_.index(answer)])

相关问题 更多 >