我刚刚为 python 制作了这个简短的代码。这是学校的时间表。我不经常使用字典,因为这是我总是感到困惑的部分。
我在代码中想要的是 print(monday["Period 1"])
,其中 我重复了 5 次 ,需要清理,所以它只需要一行代码。
我在想也许我应该使用 for 循环。但是由于我并没有真正使用 for 循环,所以我不知道如何正确使用它们。除了一两次。
这是我到目前为止完成的代码 。
monday = {"P1" : "1 - English",
"P2" : "2 - Maths",
"P3" : "3 - PE",
"P4" : "4 - Computing",
"P5" : "5 - Computing"}
choice_day = input("What day would you like to know what you have? ")
choice_period = input("What period? Or just type NO if you want to know the full day: ")
if choice_day == "monday" and choice_period == "NO":
print(monday["P1"])
print(monday["P2"])
print(monday["P3"])
print(monday["P4"])
print(monday["P5"])
最佳答案
字典中所有值的列表作为 monday.values()
存在
if choice_day == "monday" and choice_period == "NO":
for v in monday.values():
print v
或者您可以将列表中的每个值放入一个由换行符连接的字符串中:
if choice_day == "monday" and choice_period == "NO":
print '\n'.join(monday.values())
如果它们应该是有序的,请使用
sorted
:if choice_day == "monday" and choice_period == "NO":
print '\n'.join(sorted(monday.values()))
关于python - 缩短在字典中打印单个值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19013204/