为了简单起见,假设我使用的列表如下:

[['Bob', 'Pizza', 'Male'], ['Sally', 'Tacos', 'Female']]


我想问用户他们想查看哪些人的统计信息,以便在调用它时可以打印出BobPizzaMale。我尝试使用索引方法,但是我正在使用的列表列表有150多个条目。

我试图使用类似:

personName = input("Enter the person whose stats you would like to see: )
personIndex = personList.index(personName)
personStats = personList[personName][1:3]  # first index is the name, index 1 and 2 is favorite food and gender
print(personStats)


但这是行不通的。

最佳答案

如果您确实要使用索引,可以按照以下方式进行操作:

lst=[['Bob', 'Pizza', 'Male'], ['Sally', 'Tacos', 'Female']]
personName = input("Enter the person whose stats you would like to see:" )
ind = [i[0] for i in lst].index(personName)
food, gender = lst[ind][1:]
Print "{0} is a {1} , a {2} lover".format(personName, gender, food)

08-17 20:52