我需要删除字符串中重复字母的元素

问题描述 投票:0回答:3
String1 = “Python is an interpreted high level general purpose programming language”
List1 = String1.split()

for i in List1:
    for j in i:
        if i.count(j)>1:
            List1.remove(i)
            break
    
print(“ “.join(List1))

输出:

Python是一种高级通用编程

预期输出:

Python 是一个

让我知道我所犯的错误

python-3.x list for-loop nested break
3个回答
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)
    断言这个相同的字符出现在单词的后面

0
投票

一个问题是在迭代列表时从列表中删除。用您想要的元素重建列表几乎总是更有用: List1 = [i for i in List1 if len(i) == len(set(i))] # ['Python', 'is', 'an']

将字符串转换为集合可以删除重复的字母。因此与原始字符串的长度进行比较。您只保留那些只有唯一字母的。

© www.soinside.com 2019 - 2024. All rights reserved.