请纠正我的程序。我需要删除字符串中重复字母的元素

问题描述 投票:0回答:2

String1 =“Python 是一种解释型高级通用编程语言”

List1 = String1.split()

对于列表 1 中的 i:

对于 i 中的 j:

 if i.count(j)>1:

     List1.remove(i)

     break

打印(“”.join(List1))

输出:Python是一种高级通用编程

预期输出:Python 是一个

让我知道我犯的错误

python-3.x list for-loop nested break
2个回答
0
投票

试试这个代码

String1 = "Python is an interpreted high level general purpose programming language"
List1 = String1.split()
ResultList = []

for i in List1:
    has_repeated_letter = False
    for j in i:
        if i.count(j) > 1:
            has_repeated_letter = True
            break
    if not has_repeated_letter:
        ResultList.append(i)

print(" ".join(ResultList))

0
投票

使用正则表达式方法:

inp = "Python is an interpreted high level general purpose programming language"
words = inp.split()
output = [x for x in words if not re.search(r'(\w)(?=.*\1)', x)]
print(output)  # ['Python', 'is', 'an']

此处使用的正则表达式模式将匹配任何字符出现两次或多次的任何单词:

  • (\w)
    匹配任何单个字母并捕获
    \1
  • (?=.*\1)
    断言这个相同的字符出现在单词的后面
© www.soinside.com 2019 - 2024. All rights reserved.