如何在Python中从列表和返回结果列表(元素没有与其他元素的长度相似的长度)中匹配元素的索引?
我有一个很大的TXT文件。我想阅读文件的每一行,并根据文件的第三元素获取输入(列表)。
因此,我将文本文件转换为列表并遍历列表的每个元素以获取所需的输出。
这是我的txt文件的一部分:
34566---There was no file in there---Mr. [email protected]
36122---I found the file in [email protected]
64322
28890---I went to see the crowd---Henry [email protected]
44533---The weather made it perfect---Merry [email protected]
这是我使用的代码:
value = input("Enter your name:")
filename = open("test.txt", "r")
for line in filename:
line_num = line.strip('\n').split("---")
if line_num [2] == value:
print(line_num[1])
break
唯一的问题是中间的值,并不是列表中的其他元素。因此,它给出了一个错误,
IndexError: list index out of range
我不知道如何编码如何忽略中间元素,而中间元素并非列表中的其余元素。请帮我。
I have a very big txt file. I want to read through each line of the file and get an input based on the 3rd element of the file(list).
So, I convert the text file to list and iterate through each element of the list to get my desired output.
This is a part of my txt file:
34566---There was no file in there---Mr. [email protected]
36122---I found the file in [email protected]
64322
28890---I went to see the crowd---Henry [email protected]
44533---The weather made it perfect---Merry [email protected]
This is the code that I used:
value = input("Enter your name:")
filename = open("test.txt", "r")
for line in filename:
line_num = line.strip('\n').split("---")
if line_num [2] == value:
print(line_num[1])
break
The only problem is the value in the middle doesnot behave as the other elements in the list. So, it is giving an error
IndexError: list index out of range
I don't know how to code to ignore the middle element which doesnot behave as the rest of the elements in the list. Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试一下,
如您所见
You can try this,
As You can see I added only the
if line == '\n': continue
part which basically skips the empty line将您的病情更改为:
Change your condition to: