[英]How can I remove specific duplicates from a list, rather than remove all duplicates indiscriminately?
在 python 腳本中,我需要評估一個字符串是否包含特定字符(例如“f”)的重復項,如果是,則刪除除該字符的第一個實例之外的所有字符。 字符串中的其他字符也可能有重復項,但腳本不應刪除指定字符以外的任何重復項。
這是我到目前為止所得到的。 腳本運行,但未完成所需的任務。 我修改了這個問題的最佳答案中的 reduce() 行,但它比我此時學到的要復雜一些,所以我很難說出哪一部分是錯誤的。
import re
from functools import reduce
string = "100 ffeet"
dups = ["f", "t"]
for char in dups:
if string.count(char) > 1:
lst = list(string)
reduce(lambda acc, el: acc if re.match(char, el) and el in acc else acc + [el], lst, [])
string = "".join(lst)
讓我們創建一個 function,它接收一個字符串s
和一個字符c
作為參數,並返回一個新字符串,其中除了s
中第一次出現的c
的所有內容都被刪除。
我們將使用 Python 標准庫中的以下函數:
str.find(sub)
:返回找到 substring sub 的字符串中的最低索引。str.replace(old, new)
:返回字符串的副本,其中所有出現的 substring old 都替換為 new。這個想法很簡單:
s
中找到c
的第一個索引
s
c
的s
c
s
的第一部分與更新后的 substring 連接起來在 Python:
def remove_all_but_first(s, c):
i = s.find(c)
if i == -1:
return s
i += 1
return s[:i] + s[i:].replace(c, '')
現在你可以使用這個 function 來刪除你想要的所有字符。
def main():
s = '100 ffffffffeet'
dups = ['f', 't', 'x']
print('Before:', s)
for c in dups:
s = remove_all_but_first(s, c)
print('After:', s)
if __name__ == '__main__':
main()
這是您可以做到的一種方法
string = "100 ffeet"
dups = ["f", "t"]
seen = []
for s in range(len(string)-1,0,-1):
if string[s] in dups and string[s] in seen:
string = string[:s] + '' + string[s+1:]
elif string[s] in dups:
seen.append(string[s])
print(string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.