【问题标题】:how to find the element using index method from a list如何使用索引方法从列表中查找元素
【发布时间】:2017-02-27 14:15:10
【问题描述】:

我正在使用包含数据的日志文件。我使用 python 将文本文件转换为列表,现在我想使用 index() 方法打印出文件中提到的用户。

file = open("live.txt", 'r')
result = [line.split(' ') for line in file.readlines()]
result.index(10)

我知道该用户在列表中的第 10 号元素中被提及,但由于某种原因我没有打印出用户名。

【问题讨论】:

  • "ValueError: '10' is not in list" 是我收到的错误消息
  • ...您在寻找result[10]吗?
  • string.split 返回一个列表,这意味着 result 将是一个列表列表。也许将其定义为result = [x for line in file.readlines() for x in line.split(' ')]
  • 祝你调试顺利。
  • 记住索引从0开始,所以第十个元素实际上是索引9

标签: python list indexing


【解决方案1】:

如果您想要列表中的一个元素并且您知道它的索引,请不要使用index 方法,而是使用下标(A.K.A. 方括号)。

>>> file = open("live.txt", 'r')
>>> result = [line.split(' ') for line in file.readlines()]
>>> print(result[10])
['Hello,', "I'm", 'the', 'text', 'that', 'lives', 'on', 'the', 'eleventh', 'line', 'of', 'live.txt']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 2020-08-09
    • 2019-12-31
    相关资源
    最近更新 更多