Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:删除列表中具有重复字母的所有单词_Python_List_Loops - Fatal编程技术网

python:删除列表中具有重复字母的所有单词

python:删除列表中具有重复字母的所有单词,python,list,loops,Python,List,Loops,我正试图从包含重复字母的列表中删除所有单词(以“d”和“r”开头进行测试),但无法让它检查我希望它检查的所有字母 a = ["word","worrd","worrrd","wordd"] alpha = ['d','r'] i = 0 x = 0 while x in range(0, len(alpha)): while i in range(0, len(a)): if a[i].count(alpha[x]) > 1: del(a[i

我正试图从包含重复字母的列表中删除所有单词(以“d”和“r”开头进行测试),但无法让它检查我希望它检查的所有字母

a = ["word","worrd","worrrd","wordd"]
alpha = ['d','r']
i = 0
x = 0
while x in range(0, len(alpha)):
    while i in range(0, len(a)):
        if a[i].count(alpha[x]) > 1:
            del(a[i])
            i = i - 1
        else:
            i = i + 1
    x = x + 1
print(a)

这只是您的方法,除了我刚刚在第一个while循环之后添加了I=0

a = ["word","worrd","worrrd","wordd"]
alpha = ['d','r']
i = 0
x = 0
while x in range(0, len(alpha)):
    i = 0
    while i in range(0, len(a)):
        if a[i].count(alpha[x]) > 1:
            del(a[i])
            i = i - 1
        else:
            i = i + 1
    x = x + 1
print(a)

['word']
使用函数的简短解决方案:

import re

a = ["word","worrd","worrrd","wordd"]
result = [w for w in a if not re.search(r'([dr]).*\1', w)]

print(result)
a = ["word","worrd","worrrd","wordd"]
alpha = ['d','r']
result = [w for w in a if all(w.count(c) == 1 for c in alpha)]

print(result)
输出:

[word]

([dr]).*\1
-用于检查字符类
[dr]
中的某个字母在一个单词中是否至少出现两次的正则表达式模式

*
-匹配0个或更多字符

\1
-指向第一个捕获的组
(…)


另一个简短的替代方案是使用内置功能:

import re

a = ["word","worrd","worrrd","wordd"]
result = [w for w in a if not re.search(r'([dr]).*\1', w)]

print(result)
a = ["word","worrd","worrrd","wordd"]
alpha = ['d','r']
result = [w for w in a if all(w.count(c) == 1 for c in alpha)]

print(result)

你做得对,但是你忘了在x的while循环中重置“i”的值

a = ["word","worrd","worrrd","wordd"]
alpha = ['d','r']
x = 0
while x in range(0, len(alpha)):
    # i should be reset here
    i = 0
    while i in range(0, len(a)):
        if a[i].count(alpha[x]) > 1:
            del(a[i])
            i = i - 1
        else:
            i = i + 1
    x = x + 1
print(a)

你可能追求的是,当你有两个d:s或r:s在一排。那么您需要一个正则表达式,如下所示:

import re

a = ["word","worrd","worrrd","wordd", "worded"]
result = [w for w in a if not re.search(r'(dd)|(rr)', w)

print(result)

这也会错误地标记单词,比如
香蕉
@l3via,而他只想检查d和r。那么,
骑手
。用d和r重复字母,而不是两者都重复。这就是我在看到他的程序和他的问题后能够解释的。我想保留我的方法,但它只检查alpha的第一个字符list@EllisRourke,检查我的替代方法您没有在“x”循环中重置i,因此,这会导致下一个字符的匹配出现问题。谢谢,不知道我是如何错过的。:)