【问题标题】:How to access an entry in a list of lists and print the other entries in that list如何访问列表列表中的条目并打印该列表中的其他条目
【发布时间】:2016-05-02 10:37:03
【问题描述】:

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

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

我想询问用户他们想查看哪个人的统计信息,以便在调用时打印出BobPizzaMale。我尝试使用 index 方法,但我正在使用的列表列表中有超过 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)

但它不起作用。

【问题讨论】:

  • 你应该使用 dict() 其中名称是键

标签: python list


【解决方案1】:

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

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) 

【讨论】:

    【解决方案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 以首先获取值,这样您就不必担心查找索引的额外处理时间该索引处的值。

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 1970-01-01
      • 2022-08-19
      • 2019-11-01
      • 2015-03-16
      • 2018-01-23
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      相关资源
      最近更新 更多