使用列表和字典在 Python 中一起列印變位詞
在本教程中,我們將編寫一個程式,該程式使用列表和字典來查詢和列印變位詞。我們對每個問題都有不同的方法。嘗試在不遵循教程的情況下編寫程式碼。如果你無法產生任何想法來編寫邏輯,請按照以下步驟操作。
演算法
1. Initialize a list of strings. 2. Initialize an empty dictionary. 3. Iterate through the list of strings. 3.1. Sort the string and check if it is present in the dictionary as key or not. 3.1.1. If the sorted string is already present dictionary as a key then, append the original string to the key. 3.2 Else map an empty list with the sorted string as key and append the original to it. 4. Initialize an empty string. 5. Iterate through the dictionary items. 5.1. Concatenate all the values to the empty string. 6. Print the string.
讓我們為上述演算法編寫程式碼。
示例
## initializing the list of strings
strings = ["apple", "orange", "grapes", "pear", "peach"]
## initializing an empty dictionary
anagrams = {}
## iterating through the list of strings
for string in strings:
## sorting the string
key = "".join(sorted(string))
## checking whether the key is present in dict or not
if string in anagrams.keys():
## appending the original string to the key
anagrams[key].append(string)
else:
## mapping an empty list to the key
anagrams[key] = []
## appending the string to the key
anagrams[key].append(string)
## intializing an empty string
result = ""
## iterating through the dictionary
for key, value in anagrams.items():
## appending all the values to the result
result += "".join(value) + " "
## printing the result
print(result)輸出
如果你執行上述程式,你將獲得以下輸出。
apple orange grapes pear peach
結論
如果你對本教程有任何疑問,請在評論區提出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP