Python 如何访问列表中的条目并打印该列表中的其他条目
为了简单起见,假设我使用如下列表:Python 如何访问列表中的条目并打印该列表中的其他条目,python,list,Python,List,为了简单起见,假设我使用如下列表: [['Bob', 'Pizza', 'Male'], ['Sally', 'Tacos', 'Female']] 我想询问用户他们希望查看哪个人的统计数据,以便在调用时打印出Bob、Pizza、以及Male。我尝试使用索引方法,但是我正在使用的列表列表有超过150个条目 我试着使用类似于: personName = input("Enter the person whose stats you would like to see: ) personIndex
[['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)
但它不起作用。如果您真的想使用索引,可以按如下方式操作:
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)
Ahsanul的方法不是很有效,因为它获取每个列表的第一项,即使第一项匹配。我的车短路了:
index = next(i for i, v in enumerate(personList) if v[0] == personName)
如果它可能不存在,您可以使用如下默认值:
index = next((i for i, v in enumerate(personList) if v[0] == personName)), my_default)
如果您希望索引只获取值,请将第一个i
更改为av
以获取第一位的值,这样您就不必担心在该索引处查找值的额外处理时间。您应该使用dict(),其中名称是键