我试图删除列表中包含重复字母的所有单词(以' 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)
答案 0 :(得分:2)
使用re.search()函数的简短解决方案:
import re
a = ["word","worrd","worrrd","wordd"]
result = [w for w in a if not re.search(r'([dr]).*\1', w)]
print(result)
输出:
[word]
([dr]).*\1
- 正则表达式模式,用于检查字符类[dr]
中的某些字母是否在单词中出现至少两次
.*
- 匹配0个或更多字符
\1
- 指向第一个捕获的群组(...)
另一个简短的替代方案是使用内置的all()函数:
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)
答案 1 :(得分:0)
这是你的方法,只是我在第一次循环后添加了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']
答案 2 :(得分:0)
你做得对,但你忘了重置" i"在while循环中
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)
答案 3 :(得分:0)
你可能会追求的是,当你连续两个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)