从列表中删除在Python3中具有重复字符的单词

时间:2017-08-18 14:24:07

标签: python list

当我运行此代码时:

li=["It","is","funny","how","I","fiddled","with","this"]
for i in range(0,len(li)):
    word=li[i]
    for j in range(0,len(word)-1):
        if word[j] == word[j+1]:
            li.pop(i)
            break
print(li)

我想要的输出是:

['It','is','how','I','with','this']

但是,我收到以下错误消息:

Traceback (most recent call last):
File "fiddle.py", line 3, in <module>
word=li[i]
IndexError: list index out of range

请在我的代码中指出错误。

3 个答案:

答案 0 :(得分:2)

最简单的方法是使用正则表达式来识别字符串中相同字符的重复运行,并将其放在list-comp中,例如:

import re

li=["It","is","funny","how","I","fiddled","with","this"]
wanted = [el for el in li if not re.search(r'(.)\1', el)]

给你:

['It', 'is', 'how', 'I', 'with', 'this']

答案 1 :(得分:0)

这个怎么样:

new_list = [x for x in li if len(x) == len(set(x))]

此外,您不应该迭代列表并删除元素。最好的方法是创建一个新的

如果你想要删除2个相同的字符:

new_list = [x for x in li if not re.search(r'([a-zA-Z])\1', x)]

答案 2 :(得分:0)

此时:

for i in range(0,len(li)):

len(li)等于8,所以你的循环从0到7.但是,由于你要从循环内的li中删除项目,li变得比i之前的{8}元素短{1}}达到7.然后你得到错误。