当前位置: 首页 > 编程笔记 >

使用清单和字典在Python中一起打印字谜

邹祺
2023-03-14
本文向大家介绍使用清单和字典在Python中一起打印字谜,包括了使用清单和字典在Python中一起打印字谜的使用技巧和注意事项,需要的朋友参考一下

在本教程中,我们将编写一个程序,该程序使用listdictionary查找和打印字谜。对于每个问题,我们都有不同的方法。尝试编写代码而不遵循本教程。如果您不能产生任何想法来编写逻辑,请执行以下步骤。

算法

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

结论

 类似资料:
  • 问题内容: 这是字典 使用这个 它打印以下内容: 但是我希望程序像这样打印它: 我刚刚开始学习字典,所以不确定如何执行此操作。 问题答案: 输出:

  • 问题内容: 结果显示 该代码打印所有单词并计数频率单词的使用。 我想在单独的行中打印字典。 有任何可行的方法吗? 问题答案:

  • 问题内容: 我有两本字典,我希望能够使它们合二为一: 像这样的伪Python会很不错: 问题答案: 如果您有兴趣在不使用中间存储的情况下创建新字典:(这比使用dict.items()更快,而且我认为这更干净) 或者,如果您很乐意使用现有字典之一:

  • 问题内容: 我想像这样从python字典输出键值对: 我以为我可以这样做: 但是很明显,这不是和不争论的方式。 问题答案: 您现有的代码只需进行一些调整。 是 关键,因此您只需要使用它: 您还可以获得包含键和值的迭代器。在Python 2中,返回(键,值)元组的列表,而返回提供相同值的迭代器: 在Python 3中,返回迭代器;要获得列表,您需要将迭代器传递给自己。

  • 问题内容: 我正在为我的GCSE学习,其中一部分要求我打印按字母顺序排序的字典,并且打印内容应包含相关值。 我花了数小时试图找到答案,并浏览了该论坛上的各种帖子,但对于我的有限知识而言,大多数帖子太过复杂。 我可以打印按字母顺序排序的键,也可以打印排序后的值,但不能打印按字母顺序排序的键(附带值)。 这是我的简单测试代码 我需要打印带有值的排序键-怎么做? 问题答案:

  • 我想从python字典中输出键值对,如下所示: 我想我可以这样做: 但是很明显,事情不是这样的,因为和不接受参数。