我是一个新的程序员,试图学习如何编码。我仍然不太了解所有的技术信息。我尝试在字典列表上使用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是的,有一个更简单的方法没有嵌套循环,但我仍然需要他们嵌套。谢谢!
不需要额外的for和while循环。枚举函数给你索引,通过传递类型键你可以得到它的值。
for index, a in enumerate(Dogs_in_Shelter):
print("{} {}".format(index, a["type"]))
使用嵌套for循环
这里我使用了计数器length = 0
。我们应该用if代替while来检查计数器
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
- 你只需要一个
for
循环你想要的。while
回路也不需要。例如,
for index, dog in enumerate(Dogs_in_Shelter):
print(index, dog['type'])
- 对于Python,我们不使用大写字母表示变量。仅供参考,Python命名约定在这种情况下,
Dogs_in_Shelter
应该是dogs_in_shelter
,或简称dogs
。