gpt4 book ai didi

python - 仅删除 alpha 重复项

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:07 25 4
gpt4 key购买 nike

在 Python 中,我想从字符串中删除重复的字母,而不是数字或空格。我想到了:

result = []
seen = set()
for char in string:
if char not in seen:
seen.add(char)
result.append(char)
return "".join(result)

但这使得:

>>> delete_duplicate_letters("13 men were wounded in an explosion yesterday around 3:00pm.")
13 menwroudiaxplsyt:0.

当我想要的时候:

>>> delete_duplicate_letters("13 men were wounded in an explosion yesterday around 3:00pm.")
13 men wr oud i a xpls yt 3:00.

我尝试使用 letter 而不是 charisalpha() 函数和 if int语句等,但我什么也做不了。

最佳答案

>>> from string import digits, whitespace
>>> from collections import OrderedDict
>>> s = set(whitespace + digits)
>>> ''.join(OrderedDict((object() if c in s else c, c) for c in text).values())
'12 men wr oud i a xpls yt 3:00.'

object() 这里只是用来确保你想留下的字符的键是 always unique 因为 object() 创建每次一个不同的对象。其他字符本身用作键,因此会过滤重复项。

关于python - 仅删除 alpha 重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com