简体   繁体   English

列表索引超出范围…:(

[英]List index out of range… :(

I've tried to understand why ' if len(w) == 0: continue ' is necessary, but I can't really understand it. 我试图理解为什么' if len(w) == 0: continue '是必要的,但是我真的无法理解。 if I say only look if the 2 word matches wk and if I say the first word must be 'From'. 如果我说只看两个单词是否匹配wk并且我说第一个单词必须是“ From”。 I'm not saying that the phrase has more than 0 words? 我不是说这个短语有0个以上的单词吗?

Exercise 2: Figure out which line of the above program is still not properly guarded. 练习2:找出上述程序的哪一行仍然没有得到适当的保护。 See if you can construct a text file which causes the program to fail and then modify the program so that the line is properly guarded and test it to make sure it handles your new text file. 查看是否可以构造一个导致程序失败的文本文件,然后修改该程序,以使该行受到适当保护,并对其进行测试以确保它可以处理新的文本文件。

f = open ('mbox.txt')
wk = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat']

for l in f :
    w = l.split()
    if len(w) == 0: continue #why is this necessary????


    if w[0] != ('From'): continue # si la primera palabra es un "from", pues pasa hacia delate

    if w[2]  in wk :
        print (w[2])

Thanks for your help :) 谢谢你的帮助 :)

Consider the following points: 请考虑以下几点:

  • You do not know how many words there are in a line. 您不知道一行中有多少个单词。
  • You can only access the i-th entry of a list if there are at least i entries in that list (otherwise you will get an index out of range error). 如果该列表中至少有i个条目,则只能访问该列表的第i个条目(否则,您将获得索引超出范围错误)。

Thus if you want to check if the 3rd entry (ie words[2] ) of a list has a particular value you first have to guarantee that there are at least 3 entries in that list (ie something like len(words) >= 3 ) before you can check if the value of that word matches your expectation (ie words[2] == 'some-value' ). 因此,如果您要检查列表的第3个条目(即words[2] )是否具有特定值,则必须首先确保该列表中至少有3个条目(即len(words) >= 3 ),然后才能检查该单词的值是否符合您的期望(即words[2] == 'some-value' )。

This occurs when there is no third element in the list. 当列表中没有第三个元素时,就会发生这种情况。 I'm not clear why you're checking for the third element (I assume it's second element). 我不清楚您为什么要检查第三个元素(我假设它是第二个元素)。

You can do: 你可以做:

for l in f:
    w = l.split()
    if len(w) >= 2 and w[0] == 'From' and w[1] in wk:
        print(w[1])

Now this prints second word in a line from file if that line starts with 'From' and the second word is available in wk . 现在,如果文件行中的第二个单词以'From'开头并且第二个单词在wk可用,则此命令将在该行中输出第二个单词。

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

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