Python遍历列表时取模判断换行结果不一致问题
问题背景
- 现有一个存储字符串的列表
passage,需求是将拆分后的单词按每5个单词拼接为一行,判断逻辑为:索引值加1后对5取模,结果为0时在对应单词后添加换行符。 - 运行代码后逻辑大部分正常,但会无规律跳过部分索引为5的倍数的位置,具体跳过了索引40、45、55,输出结果不符合预期,无法定位问题。
存在问题的原始代码如下:
for word in passage: indx = passage.index(word) # 获取索引存入变量indx if (indx+1) %5 == 0: # 每第5个元素触发逻辑 passage[indx] = f"{word}\n{indx+1}" # 给元素加换行和索引序号 print(passage) print() final = " ".join(passage) print(final)
异常输出
修改后的列表输出
['When', 'in', 'the', 'Course', 'of\n5', 'human', 'events,', 'it', 'becomes', 'necessary\n10', 'for', 'one', 'people', 'to', 'dissolve\n15', 'the', 'political', 'bands', 'which', 'have\n20', 'connected', 'them', 'with', 'another,', 'and\n25', 'to', 'assume', 'among', 'the', 'powers\n30', 'of', 'the', 'earth,', 'the', 'separate\n35', 'and', 'equal', 'station', 'to', 'which', 'the', 'Laws', 'of', 'Nature', 'and', 'of', "Nature's", 'God', 'entitle', 'them,\n50', 'a', 'decent', 'respect', 'to', 'the', 'opinions', 'of', 'mankind', 'requires', 'that\n60', 'they', 'should', 'declare', 'the', 'causes\n65', 'which', 'impel', 'them', 'to', 'the', 'separation.']
拼接后的字符串输出
When in the Course of 5 human events, it becomes necessary 10 for one people to dissolve 15 the political bands which have 20 connected them with another, and 25 to assume among the powers 30 of the earth, the separate 35 and equal station to which the Laws of Nature and of Nature's God entitle them, 50 a decent respect to the opinions of mankind requires that 60 they should declare the causes 65 which impel them to the separation.
原始passage列表内容
['When', 'in', 'the', 'Course', 'of', 'human', 'events,', 'it', 'becomes', 'necessary', 'for', 'one', 'people', 'to', 'dissolve', 'the', 'political', 'bands', 'which', 'have', 'connected', 'them', 'with', 'another,', 'and', 'to', 'assume', 'among', 'the', 'powers', 'of', 'the', 'earth,', 'the', 'separate', 'and', 'equal', 'station', 'to', 'which', 'the', 'Laws', 'of', 'Nature', 'and', 'of', "Nature's", 'God', 'entitle', 'them,', 'a', 'decent', 'respect', 'to', 'the', 'opinions', 'of', 'mankind', 'requires', 'that', 'they', 'should', 'declare', 'the', 'causes', 'which', 'impel', 'them', 'to', 'the', 'separation.']
问题根因
问题出在indx = passage.index(word)这行代码,是Python初学者非常容易踩的坑:
list.index(x)方法的作用是返回列表中第一个值等于x的元素的索引,它不会自动返回当前循环迭代到的元素的位置。- 传入的
passage列表里存在大量重复单词,比如the、of、to、which都多次出现。当循环遍历到这些重复单词时,index()拿到的是该单词在列表里第一次出现的下标,不是当前元素的真实下标,后续的取模判断自然就会出错。 - 再加遍历过程中会直接修改列表元素(给匹配到的单词加换行和序号),导致前面位置的原单词被替换后,后续重复单词调用
index()时匹配到的位置更加混乱,最终表现为部分5倍数索引被无规律跳过。
以索引40位置为例,该位置的单词是which,但which第一次出现在索引18的位置,当循环走到索引40的which时,passage.index("which")返回18,(18+1)%5 = 4,不满足等于0的判断条件,这个位置的换行逻辑就被直接跳过了。
修复方案
遍历列表需要同时拿到元素和对应索引时,直接用Python内置的enumerate()函数即可,不要靠index()方法查找索引,修复后的代码如下:
for idx, word in enumerate(passage): if (idx + 1) % 5 == 0: passage[idx] = f"{word}\n{idx+1}" final = " ".join(passage) print(final)
运行后就能得到每5个单词换一行的正确结果,不会再出现索引跳过的问题。
内容的提问来源于stack exchange,提问作者Charles Ellmaker
相关产品推荐
相关产品推荐

