我正在使用 python 3.9 并嘗試從 python 串列和 python 字典中獲取資訊并遍歷它以進行回圈。根據單位,將從字典中獲取正確的電子郵件地址。
當我執行我的代碼時,它會在串列的每個成員上回圈三遍,我不知道如何讓它不這樣做。我相信最初的 for 回圈執行正常并獲得金屬,但它是否是第二個回圈使其每個專案運行 3 次,我該如何修復它?
我意識到這很奇怪,但我一定是在某個地方犯了根本性的錯誤,在過去 5 個小時試圖弄清楚之后,現在是尋求幫助的時候了。
# Dictionary of metals and email addresses
metals = {
'gold':'[email protected]',
'silver':'[email protected]',
'platinum':'[email protected]',
}
# Variable holding some string data
gold = """
Gold is a chemical element with the symbol Au and atomic number 79,
"""
silver = """
Silver is a chemical element with the symbol Ag and atomic number 47.
"""
platinum = """
Platinum is a chemical element with the symbol Pt and atomic number 78.
"""
units = [gold, silver, platinum]
# What I want to do is have a loop where it takes the item in the list
#, for example, gold, matches it with the key to that in the dictionary, thereby
# enabling me to send gold to [email protected], silver to [email protected], and platinum to
# 3gmail.com
for unit in units:
for metal in metals.items():
if unit == gold:
email_address = metals.get('gold')
print(email_address)
elif unit == silver:
email_address = metals.get('silver')
print(email_address)
elif unit == platinum:
email_address = metals.get('platinum')
print(email_address)
else:
print('No Match')
# just some code to print out various bits of information
# Print our Dictionary Keys
for k in metals.keys():
print('Keys: ' k)
# Print our dictionary Values
for v in metals.values():
print('Values: ' v)
# print out the values held in our list
for item in units:
print('Items: ' item)
這是輸出:
1@gmail.com
1@gmail.com
1@gmail.com
2@gmail.com
2@gmail.com
2@gmail.com
3@gmail.com
3@gmail.com
3@gmail.com
Keys: gold
Keys: silver
Keys: platinum
Values: 1@gmail.com
Values: 2@gmail.com
Values: 3@gmail.com
Items:
Gold is a chemical element with the symbol Au and atomic number 79,
Items:
Silver is a chemical element with the symbol Ag and atomic number 47.
Items:
Platinum is a chemical element with the symbol Pt and atomic number 78.
uj5u.com熱心網友回復:
只需洗掉內部for回圈,更改此:
for unit in units:
for metal in metals.items():
if unit == gold:
email_address = metals.get('gold')
print(email_address)
elif unit == silver:
email_address = metals.get('silver')
print(email_address)
elif unit == platinum:
email_address = metals.get('platinum')
print(email_address)
else:
print('No Match')
對此:
for unit in units:
if unit == gold:
email_address = metals.get('gold')
print(email_address)
elif unit == silver:
email_address = metals.get('silver')
print(email_address)
elif unit == platinum:
email_address = metals.get('platinum')
print(email_address)
else:
print('No Match')
沒有規則說您需要迭代metals才能呼叫metals.get.
uj5u.com熱心網友回復:
中有 3 個專案metals.items()。這就是回圈運行 3 倍的原因。只需洗掉該陳述句;你不需要那個回圈
for unit in units:
if unit == gold:
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377159.html
