![](/img/trans.png)
[英]How to keep the first occurence of a value which is repeated in a dataframe in python?
[英]How to remove the first occurence of a repeated Character with python
我得到了以下字符串'abcdea'
,我需要找到重復的字符,但刪除第一個字符,因此結果大部分是'bcdea'
我曾嘗試遵循但只能得到這個結果
def remove_rep(x):
new_list = []
for i in x:
if i not in new_list:
new_list.append(i)
new_list = ''.join(new_list)
print(new_list)
remove_rep('abcdea')
結果是'abcde'
而不是我正在尋找的'bcdea'
一種方法可以是在字符串上以相反的順序迭代,並跟蹤字符串中看到的所有字符。 如果一個字符重復,我們不會將它添加到new_list
。
def remove_rep(x: str):
new_list = []
seen = set()
for char in reversed(x):
if char not in seen:
new_list.append(char)
seen.add(char)
return ''.join(reversed(new_list))
print(remove_rep('abcdea'))
結果: 'bcdea'
請注意,上述解決方案並不完全按預期工作,因為它會刪除除最后一個字符之外的所有字符; 例如,如果一個字符出現了 2 次以上,而您只想刪除第一個。 要解決這個問題,您可以改為執行以下操作:
def remove_rep(x: str):
new_list = []
first_seen = set()
for char in x:
freq = x.count(char)
if char in first_seen or freq == 1:
new_list.append(char)
elif freq > 1:
first_seen.add(char)
return ''.join(new_list)
現在對於給定的輸入:
print(remove_rep('abcdeaca'))
我們得到了想要的結果——只刪除了第a
和c
:
bdeaca
測試更復雜的輸入:
print(remove_rep('abcdeaabcdea'))
我們確實得到了正確的結果:
aabcdea
你看到最后一個發生了什么嗎? 第一個abcde
序列被刪除,因為在這個字符串中所有字符都重復了。 所以我們的結果實際上是正確的,盡管乍一看並不如此。
您可以使用str.find()
,它返回第一次出現的字符串:
def remove_rep(oldString):
newString = ''
for i in oldString:
if i in newString:
# Character used previously, .find() returns the first position within string
first_position_index = newString.find(i)
newString = newString[:first_position_index] + newString[
first_position_index + 1:]
newString += i
print(newString)
remove_rep('abcdea')
remove_rep('abcdeaabcdea')
出去:
bcdea
bcdea
在if
條件中有一個小的變化的方法之一:
def remove_rep(x):
new_list = []
visited = []
for i, item in enumerate(x):
if item not in x[i+1:] or item in visited:
new_list.append(item)
else:
visited.append(item)
new_list = ''.join(new_list)
print(new_list)
remove_rep('abcdeaa')
remove_rep('abcdeaabcdea')
輸出:
bcdeaa
aabcdea
str.replace()
這樣做:
https://docs.python.org/3/library/stdtypes.html#str.replace
str.replace(舊的,新的[,計數])
返回字符串的副本,其中所有出現的子字符串 old 都被 new 替換。 如果給出了可選參數計數,則僅替換第一個計數出現。
所以基本上:
"abcabc".replace('b', '', 1)
# output : 'acabc'
改變
new_list = ''.join(new_list)
到
new_list = ''.join(new_list[1:]+[i])
(並找出原因!提示:你的if
塊的條件是什么?你在檢查什么,為什么?)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.