使用列表和字典在 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

結論

如果你對本教程有任何疑問,請在評論區提出。

更新日期:2019-10-23

558 次觀看

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告