【问题标题】:nested for loops and nested dictionary?嵌套for循环和嵌套字典?
【发布时间】:2021-03-09 01:44:27
【问题描述】:

我是一名新程序员,正在努力学习如何编写代码。我仍然不太了解所有的技术信息。我正在尝试在字典列表上使用 for 循环,然后在该循​​环内,我想创建另一个枚举字典键的循环。在该循环内部,然后我想打印键和值。一旦索引到达所有点,我希望循环中断。

Dogs_in_Shelter = [{
               "type" : "poodle",
               "age" : "2", 
               "size" : "s", 
               
           }, 
           {    
               "type" : "pug",
               "age" : "7", 
               "size" : "m", 
           },
           {
               "type" : "lab",
               "age" : "10",
               "size" : "m", 
           }
               ]
for a in Dogs_in_Shelter:
 for index, a in enumerate(Dogs_in_Shelter):
   while (index <= 2): 
     print("{} {}".format(index,a["type"]))
     index += 1 
     break

打印出来的是:

0 poodle
1 pug
2 lab
0 poodle
1 pug
2 lab
0 poodle
1 pug
2 lab

我只想要前三行(带有键和值),而不是重复。 对学习者有什么帮助吗?

edit 是的,没有嵌套循环有一种更简单的方法,但是我仍然需要将它们嵌套。谢谢!

【问题讨论】:

  • 如果你不想重复,你应该去掉多余的 forwhile 循环。你只需要一个for循环:for i, d in enumerate(Dogs_in_Shelter): print(i, d["type"])

标签: python dictionary for-loop enumerate


【解决方案1】:

不需要额外的 for 循环和 while 循环。 enumerate 函数为您提供索引,通过传递类型键您可以获得它的值。

for index, a in enumerate(Dogs_in_Shelter):
    print("{} {}".format(index, a["type"]))

使用嵌套 for 循环。

这里我使用了计数器length = 0。而不是 while 我们应该使用 if 来检查计数器。

length = 0
for a in Dogs_in_Shelter:
 for index, a in enumerate(Dogs_in_Shelter):
     if length <= 2 :
        print("{} {}".format(index,a["type"]))
        length += 1

【讨论】:

  • 感谢您的建议,但我仍然想使用额外的嵌套循环来完成此操作。还有其他建议吗? TIA
  • 额外循环的目的是什么?
  • while 循环内的 for 循环将给出重复的结果。而是使用 if- 语句来检查条件。我已经更新了答案。
【解决方案2】:
  1. 您只需要一个for 循环即可满足您的需求。 while 循环也是不必要的。例如,
for index, dog in enumerate(Dogs_in_Shelter):
    print(index, dog['type'])
  1. 对于 Python,我们不对变量使用大写字母。仅供参考,Python Naming Convention 在这种情况下,Dogs_in_Shelter 应该是 dogs_in_shelter,或者只是 dogs

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2022-06-15
    • 2018-07-13
    • 2021-07-25
    • 2019-03-29
    相关资源
    最近更新 更多