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

开启你的 职业生涯

完成课程以获得认证

开始
广告