簡體   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