背景關系: 我正在撰寫一個程式來查找字串中的第一個非重復字母。
測驗代碼 我需要實作以下邏輯:
s = "iiiiiiitya"
if 'i' in s:
s = s.replace('i','')
print(s)
輸出: tya
這很好。它從字串中洗掉所有出現的 'i'。這就是我想要的。
問題:但是一旦我開始在我的實際程式中實作相同的邏輯,該函式的作業方式就不一樣了,即它只洗掉了 perticulare 字母的第一次出現,因此我的邏輯失敗了。
def non_rep(s):
for el in s:
if el in s[1:]:
s = s.replace(el,'')
else:
return el
return "No such case is matched"
str = "adiiiityda"
ch = non_rep(str)
print(ch)
輸出:我
預期產量:噸
為什么它的行為方式如此,我嘗試了很多,但它在第一個(測驗)代碼中的作業方式應該如此,當我將它實作到程式中時,它的行為有所不同。請幫忙。
uj5u.com熱心網友回復:
您可以使用 python 中字串的函式計數,如下所示
def non_rep(s):
for char in s:
if s.count(char) == 1:
return char
uj5u.com熱心網友回復:
您應該注意字串是不可變的,因此您不能在回圈中更改它,它不會按照您想要的方式運行
def non_rep(s):
for el in s:
if el in s[1:]:
s = s.replace(el,'')
if len(s)>0:
return s[0]
return "No such case is matched"
str = "adiiiityda"
ch = non_rep(str)
print(ch)
uj5u.com熱心網友回復:
您可以使用collections.Counter來獲取計數,然后只保留唯一值:
from collections import Counter
s = "iiiiiiitya"
c = Counter(s)
''.join([i for i in c if c[i]==1])
輸出: tya
uj5u.com熱心網友回復:
以下使用while代替實作您的想法:
def non_rep(s):
while s: # while s is non-empty
el = s[0] # get the first character
if el in s[1:]: # if the character is found in another place
s = s.replace(el, '') # remove all of them
else: # if not repeated
return s[0] # return that
return 'No such case is matched' # this is reached when depleted
print(non_rep("adiiiityda")) # t
print(non_rep("aabbcc")) # No such case is matched
通常建議不要洗掉for回圈中的專案。如果你把 放在print(el, s)之后for el in s:,你會看到發生了什么。你會發現它el只是跟在原來的string后面adiiiityda。所以在第四次迭代時,el是'i'while sis 'ty'。您的代碼'i'在 中找不到它'ty',因此它回傳'i',這不是您想要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310976.html
上一篇:網頁抓取不會在html中回傳
下一篇:Pandas資料幀條件插值
