简体   繁体   English

如何从列表中使用索引方法查找元素

[英]how to find the element using index method from a list

im working with a log file containing data. 我正在处理包含数据的日志文件。 I converted the text file into a list using python, i would now like to print out the user that are mentioned in the file by using the index() method. 我使用python将文本文件转换为列表,现在我想使用index()方法打印出文件中提到的用户。

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

I know that the user is mention in element number 10 from the list, but for some reason i dont get the username printed out. 我知道用户在列表中的元素编号10中被提及,但是由于某种原因我没有打印出用户名。

If you want an element from a list and you know its index, don't use the index method, use a subscript (AKA square brackets). 如果要从列表中获取元素并且知道其索引,请不要使用index方法,而要使用下标(AKA方括号)。

>>> 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM