【发布时间】:2022-01-13 20:27:58
【问题描述】:
我正在使用 python 3.9 并尝试从 python 列表和 python 字典中获取信息并遍历它以进行循环。将根据单位从字典中获取正确的电子邮件地址。
当我执行我的代码时,它会在列表的每个成员上循环三遍,我不知道如何让它不这样做。我相信最初的 for 循环执行得很好并获得了金属,但它是第二个循环使它每个项目运行 3 次,我该如何修复它?
我意识到这很愚蠢,但我一定是在某个地方犯了根本性错误,在过去 5 个小时试图弄清楚之后,现在是寻求帮助的时候了。
# Dictionary of metals and email addresses
metals = {
'gold':'1@gmail.com',
'silver':'2@gmail.com',
'platinum':'3@gmail.com',
}
# 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 1@gmail.com, silver to 2@gmail.com, 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.
【问题讨论】:
-
内部
for循环的意义何在?您不能直接删除它,因为它正在做您实际上不想做的事情吗? -
谢谢@samwise。有时我只是想多了。我想这就是对此感到陌生的问题。只是过于复杂的事情
标签: python dictionary for-loop nested