簡體   English   中英

遍歷函數中的值

[英]Looping Through Values In Functions

所以我需要遍歷字典中的字典。 基本上,我將這樣的信息保存到字典中:

accounts = {}

def accountcreator():
  newusername = raw_input()
  newpassword = raw_input()
  UUID = 0
  UUID += 1
  accounts[newusername] = {newpassword:UUID}

然后在另一個函數中,我想遍歷所有這些值,因此例如,這就是我到目前為止所掌握的。 這樣可以正確遍歷所有新用戶名。

def accounts():
  for usernames in accounts:
    #I do not know what to do from here on out
    #I want it to loop through all of the newpasswords and UUID
    #And the UUIDs would be saved to a new variable

請幫助我,我只想簡單地回答一下如何遍歷所有值。 謝謝!

編輯所以基本上這是一個例子:

def accountcreator():
  newusername = raw_input() #For raw input I put in cool-account-name
  newpassword = raw_input() #For raw input I put in this-is-a-password
  UUID = 0
  UUID += 1
  accounts[newusername] = {newpassword:UUID} #So basically what is being saved is accounts[cool-account-name] = {this-is-a-password:1}

因此,在發生這種情況之后,我希望通過帳戶功能實現這一點。 我希望它打印每個單獨的項目,因此基本上它將打印以下每個項目:用戶名,密碼和UUID。 因此,上面提供的信息將顯示用戶名:cool-account-name,密碼:this-is-a-password和UUID:1。

您只需要在accounts [usernames]的值上添加另一個循環

def accounts():
  for usernames in accounts:
    for passwords in accounts[usernames]:
      # Here you can access the UUID you want through: accounts[usernames][passwords]

字典的工作原理不同於列表,因此您必須使用.values()或.keys()進行迭代。

accounts.keys()將返回字典中的所有鍵:

d = {1:2,3:4}

for v in d.keys():
    print (v)
# Would print 1 and 3

# And
for v in d.keys():
    print (d[v])
# Would print 2 and 4

accounts.values()將在字典中返回這些鍵的所有值:

d = {1:2,3:4}

for v in d.values():
    print (v)
# Would print 2 and 4

您還必須在每個函數中放入global accounts行,以便能夠訪問外部定義的帳戶變量。 否則,每個函數都會創建自己的account變量或給出錯誤

暫無
暫無

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

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