繁体   English   中英

删除字符串中重复的字符集 - Python

[英]Remove duplicates of set of characters in string - Python

我有一个字符串'1a1b1c1d3e3e3e1f1g2h2h1i1j1k1l1m1n4o4o4o4o1p1q2r2r1s2t2t2u2u1v1w1x1y1z'并且我想删除这些租船人的所有重复项: 3e, 4o, 2r等。我该如何在 ZA7F5113F35421B9327 中做到这一点?

str_='1a1b1c1d3e3e3e1f1g2h2h1i1j1k1l1m1n4o4o4o4o1p1q2r2r1s2t2t2u2u1v1w1x1y1z'
seen = set()
result = []
n=2
for i in range(0,len(str_),n):
    item=str_[i:i+n]
    if item not in seen:
        seen.add(item)
        result.append(item)

这是一种非常粗暴的做法。
但它似乎可以在没有开始复杂的情况下完成这项工作。

这还假设您需要删除已知的字符组合。 您没有提到您需要删除所有重复项,只需要删除一组已知的重复项。

x = '1a1b1c1d3e3e3e1f1g2h2h1i1j1k1l1m1n4o4o4o4o1p1q2r2r1s2t2t2u2u1v1w1x1y1z'
for y in ['3e', '4o', '2r']:
    x = x[:x.find(y)+len(y)] + x[x.find(y)+len(y):].replace(y, '')
print(x)

Finds the first occurance of your desired object ( 3e for instance) and builds a new version of the string up to and including that object, and prepends the string with the rest of the original string but with replacing your object with a empty string.

这有点慢,但同样可以完成工作。 这里没有错误处理,所以要小心-1位置等。

您可以通过以下方式使用列表推导和设置来执行此操作:

s = '1a1b1c1d3e3e3e1f1g2h2h1i1j1k1l1m1n4o4o4o4o1p1q2r2r1s2t2t2u2u1v1w1x1y1z' s = [s[i:i+2] for i in range(0, len(s) - 1, 2)] s = set(s)

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM