为了简单起见,假设我使用如下列表:
[['Bob', 'Pizza', 'Male'], ['Sally', 'Tacos', 'Female']]
我想询问用户他们希望查看哪个人的统计数据,以便在调用时打印出Bob
、Pizza
和Male
。我尝试使用索引方法,但是我正在使用的列表列表有超过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)
但它不起作用
Ahsanul的方法不是很有效,因为它获取每个列表的第一项,即使第一项匹配。我的车短路了:
如果它可能不存在,您可以使用如下默认值:
如果希望索引只获取值,请将第一个
i
更改为v
以获取第一个位置的值,这样就不需要担心在该索引处查找值的额外处理时间如果你真的想使用索引,你可以像下面这样做:
相关问题 更多 >
编程相关推荐