Python程式:查詢字元流中的第一個非重複字元?


在本文中,我們將找到字元流中的第一個非重複字元。假設我們的輸入如下:

Thisisit

以下應該顯示第一個非重複字元的輸出:

H

使用while迴圈查詢字元流中的第一個非重複字元

我們將透過使用迴圈比較每個字元與其他字元來查詢第一個非重複字元:

示例

# String myStr = "thisisit" # Looping while myStr != "": slen0 = len(myStr) ch = myStr[0] myStr = myStr.replace(ch, "") slen1 = len(myStr) if slen1 == slen0-1: print ("First non-repeating character = ",ch) break; else: print ("No Unique Character Found!")

輸出

No Unique Character Found!
First non-repeating character =  h

使用函式查詢字元流中的第一個非重複字元

我們還可以建立一個自定義函式並將字串傳遞給它來查詢第一個非重複字元:

示例

# Custom function def RepeatingFunc(myStr): char_order = [] counts = {} for c in myStr: if c in counts: counts[c] += 1 else: counts[c] = 1 char_order.append(c) for c in char_order: if counts[c] == 1: return c return None print("First Non-Repeating Character = ",RepeatingFunc('thisisit'))

輸出

First Non-Repeating Character =  h

使用Counter()查詢字元流中的第一個非重複字元

還可以使用Collections模組中的Counter來查詢第一個非重複字元。此模組實現專門的容器資料型別,為Python的通用內建容器dict、list、set和tuple提供替代方案:

示例

from collections import Counter def repeatFunc(myStr): freq = Counter(myStr) # Traverse the string for i in myStr: if(freq[i] == 1): print(i) break # Driver code myStr = "thisisit" repeatFunc(myStr)

輸出

h

更新於:2022年8月11日

8K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.