2017-02-27 23 views
0

即時消息處理包含數據的日誌文件。我使用python將文本文件轉換爲列表,現在我想通過使用index()方法打印文件中提到的用戶。如何從列表中找到使用索引方法的元素

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

我知道,用戶提從列表元素的10號,但由於某種原因,我不得到的用戶名打印出來。

+0

「ValueError:'10'不在列表中」是我收到的錯誤消息 – user3768971

+2

...你在找'result [10]'嗎? –

+1

'string.split'返回一個列表,這意味着'result'將成爲一個列表列表。也許將其定義爲'result = [x for line.split('')的file.readlines()中的行)' –

回答

0

如果您想要列表中的元素並知道其索引,請不要使用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'] 
相關問題