使用清单和字典在Python中一起打印字谜
在本教程中,我们将编写一个程序,该程序使用list和dictionary查找和打印字谜。对于每个问题,我们都有不同的方法。尝试编写代码而不遵循本教程。如果您不能产生任何想法来编写逻辑,请执行以下步骤。
算法
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
结论
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短