如何访问列表列表中的条目并打印该lis中的其他条目

2024-09-27 09:31:35 发布

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

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

[['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)

但它不起作用


Tags: andthe用户列表indexismalefemale
2条回答

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更改为v以获取第一个位置的值,这样就不需要担心在该索引处查找值的额外处理时间

如果你真的想使用索引,你可以像下面这样做:

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) 

相关问题 更多 >

    热门问题