如何在Python中从列表和返回结果列表(元素没有与其他元素的长度相似的长度)中匹配元素的索引?

发布于 2025-01-24 10:59:50 字数 1300 浏览 0 评论 0原文

我有一个很大的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巷子口的你 2025-01-31 10:59:51

您可以尝试一下,

value = input("Enter your name:")

filename = open("anotherSix.txt", "r")
for line in filename:
    if line == '\n':
        continue
    line_num = line.strip('\n').split("---")
    if line_num [2] == value:
        print(line_num[1])
        break

如您所见

You can try this,

value = input("Enter your name:")

filename = open("anotherSix.txt", "r")
for line in filename:
    if line == '\n':
        continue
    line_num = line.strip('\n').split("---")
    if line_num [2] == value:
        print(line_num[1])
        break

As You can see I added only the if line == '\n': continue part which basically skips the empty line

原谅我要高飞 2025-01-31 10:59:51

将您的病情更改为:

if len(line_num) > 2 and line_num [2] == value:

Change your condition to:

if len(line_num) > 2 and line_num [2] == value:
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文