如何在列表索引不超出范围的情况下两次递增

2024-04-26 20:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要迭代我的列表,这是单词和增量两次循环。按第一个增量是用l保存单词,第二个增量是用m保存i+1处的标记。我需要用一个变量迭代循环,这个变量就是我。但它给了我一个错误:列表索引超出范围。你知道吗

   i=4      
    while i<len(words): # this loop store words of a file in an array
          l=lemmatizer.lemmatize(words[i]) #array of words is lematized here
          print(l)
          i +=1
          m=words[i]
          print(m)
          if result!=0:
             #do something
           else:
              #do something  
          i+=1 

Tags: of标记列表len错误this单词array
2条回答

在python中使用while循环遍历列表通常不是最好的方法。在您希望一次取出2个元素的情况下,我将尝试执行类似于zip(words[::2], words[1::2])的操作来获得单词对的迭代器。您可以在代码中使用此选项,例如:

for l, m in zip(words[::2], words[1::2]):
    # do something with l and m

请注意,当单词长度不均匀时,这将不使用最后一个元素,如果您希望使用最后一个元素的默认值,则可以使用itertools.zip_longestzip_longest(words[::2], words[1::2], fillvalue='defaultvalue')。你知道吗

这是没有测试,但这里是:

while i<len(words)-1: # this loop store words of a file in an array
      l=lemmatizer.lemmatize(words[i]) #array of words is lematized here
      print(l)

      m=words[i+1]
      print(m)
      if result!=0:
         #do something
       else:
          #do something  
      i+=2

我认为for循环在这里会更好,但是 虽然也很管用。你知道吗

相关问题 更多 >