使用清单和字典在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 生日广州男生祝福语简短