簡體   English   中英

嵌套for循環和嵌套字典?

[英]nested for loops and nested dictionary?

我是一個新的程序員,試圖學習如何編碼。 我仍然不太了解所有的技術信息。 我正在嘗試在字典列表上使用 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

我只想要前三行(帶有鍵和值),而不是重復。 對學習者有幫助嗎?

編輯是的,沒有嵌套循環有一種更簡單的方法,但是我仍然需要嵌套它們。 謝謝!

不需要額外的 for 循環和 while 循環。 enumerate function 為您提供索引,通過傳遞類型鍵您可以獲得它的值。

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

使用嵌套 for 循環。

在這里,我使用了 counter 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
  1. 您只需要一個for循環即可滿足您的需求。 while循環也是不必要的。 例如,
for index, dog in enumerate(Dogs_in_Shelter):
    print(index, dog['type'])
  1. 對於 Python,我們不對變量使用大寫字母。 僅供參考, Python 命名約定在這種情況下, Dogs_in_Shelter應該是dogs_in_shelter ,或者只是dogs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM