Python 程式查詢字串中所有重複字元
本文將教你如何編寫一個 Python 程式來查詢字串中所有重複的字元。
在字串中重複出現的字元稱為重複字元。當我們提到列印字串中的重複字元時,我們的意思是我們將列印字串中出現兩次以上的所有字元,包括空格。
輸入-輸出場景
以下是查詢字串中所有重複字元的輸入-輸出場景:
Input: TutorialsPoint Output: t, o, i
我們可以看到,給定字串“TutorialsPoint”中的重複字元是“t”重複了“3”次,“o”重複了“2”次,“i”重複了“2”次。
演算法
以下演算法將搜尋字串中的重複字元:
建立一個字串並將其儲存在一個變數中。
要查詢重複字元,請使用兩個迴圈。使用外部迴圈選擇一個字元並將變數 count 設定為 1
為了將所選字元與字串中剩餘的字元進行比較,將使用內部迴圈。
如果找到匹配項,則將 count 增加 1。
如果內部迴圈完成後某個字元的 count 大於 1,則字串中存在重複字元。
列印字元計數和所有重複字元。
結束
我們可以透過多種方式實現上述演算法,讓我們逐一看看:
使用迴圈
要反覆遍歷序列,請使用 for 迴圈。此功能更像是在其他面向物件程式語言中看到的迭代器方法,並且不太像在其他程式語言中找到的 for 關鍵字。
示例
以下是如何使用迴圈查詢字串中所有重複字元的示例:
string = "Welcome to TutorialsPoint family"; print("All the duplicate characters in the string are: "); # Counting every characters of the string for s in range(0, len(string)): count = 1; for t in range(s+1, len(string)): if(string[s] == string[t] and string[s] != ' '): count = count + 1; # setting the string t to 0 to avoid printing the characters already taken string = string[:t] + '0' + string[t+1:]; # If the count is greater than 1, the character is considered as duplicate if(count > 1 and string[s] != '0'): print(string[s]," - ",count);
輸出
以下是上述程式碼的輸出:
All the duplicate characters in the string are: e - 2 l - 3 o - 4 m - 2 t - 3 o - 3 t - 2 o - 2 i - 3 a - 2 l - 2 i - 2
使用列表和 count() 方法
可以使用 count() 函式 統計字串中字元或子字串出現的頻率 Python 語言。作為返回值,它僅提供出現次數的計數。
示例 2
以下是如何使用 count() 方法查詢字串中所有重複字元的示例:
# initializing the string str = "tutorialspoint" # initializing a list to add all the duplicate characters duplicate_char = [] for character in str: # check whether there are duplicate characters or not # returning the frequency of a character in the string if str.count(character) > 1: # append to the list if it is already not present if character not in duplicate_char: duplicate_char.append(character) print(*duplicate_char)
輸出
以下是上述程式碼的輸出:
t o i
使用 Counter() 方法
Python 的 dict 的 Counter 子類專門用於計數可雜湊物件。它是一個 字典,其中數字是值,物件是鍵。在使用 Counter 時,通常會將可雜湊物件的序列或可迭代物件作為輸入傳遞給類的建構函式。
示例
使用 Counter() 方法,建立一個字典,其中字串作為鍵,頻率作為值。之後,建立一個臨時變數並列印從值大於 1 的鍵派生的每個索引,如下例所示:
from collections import Counter def duplicate_character(input): # creating the dictionary by using counter method having strings as key and its frequencies as value string = Counter(input) # Find the number of occurrence of a character and getting the index of it. for char, count in string.items(): if (count > 1): print(char) # Driver code if __name__ == "__main__": input = 'TutorialsPoint' duplicate_character(input)
輸出
以下是上述程式碼的輸出:
t o i