3

我刚刚为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"])
4

4 回答 4

2

字典中所有值的列表存在为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()))
于 2013-09-25T19:09:31.710 回答
1

Assuming that you want to print the values according to the alphabetically sorted keys as in your example, you can use something like the following:

if choice_day == "monday" and choice_period == "NO":
    print '\n'.join(monday[k] for k in sorted(monday))

If in your actual code the keys should be ordered in a different way than an alphabetical sort and you know what this ordering is in advance, you can do something like the following:

order = ["P1", "P2", "P3", "P4", "P5"]
if choice_day == "monday" and choice_period == "NO":
    print '\n'.join(monday[k] for k in order)
于 2013-09-25T19:13:02.270 回答
1

Surely you want to see the courses in order. dict values are inherently without order. So using a list might be more appropriate than using a dict here.

monday = ["1 - English",
          "2 - Maths",
          "3 - PE",
          "4 - Computing",
          "5 - Computing"]

if choice_day == "monday" and choice_period == "NO":
    for course in monday:
        print(course)

By not using a dict you avoid having to sort, or use a list declaring that period 1 comes before period 2, etc. (e.g. order = ['P1', 'P2', ...]). The list makes the order built-in.

If for some reason you needed to access, say, the 3rd course on Monday, since Python uses 0-based indexing, you'd write monday[2].


You may, however, want to use a dict to represent the entire schedule:

schedule = {'monday': ["1 - English",
                       "2 - Maths",
                       "3 - PE",
                       "4 - Computing",
                       "5 - Computing"]
            'tuesday': [...]}

You would use a dict here since the user may enter any day of the week. If you were always accessing the schedule in order, then you'd want to use an ordered data structure like a list or tuple.

Now you could handle any value for choice_day like this:

if choice_period == "NO":
    for course in schedule[choice_day]:
        print(course)

(Be sure to think about how you want to handle the case when the user enters a choice_day that does not exist... One possibility is to vet the choice when it is entered. Another alternative is to use a try..except here. A third -- my preference -- is to use argparse.)

Anyway, using a dict for schedule allows you to avoid mind-numbing code like:

if choice_day == 'monday':
    ...
elif choice_day == 'tuesday':
    ...
于 2013-09-25T19:13:05.453 回答
0

dict 具有values()返回给定字典中所有可用值的列表的方法。您可以简单地遍历该列表,试试这个代码:

if choice_day == "monday" and choice_period == "NO":
 for v in monday.values():
   print v

假设您只想打印密钥然后使用keys()方法而不是values()

if choice_day == "monday" and choice_period == "NO":
 for k in monday.keys():
   print k

如果你想打印两个键,值然后使用items()

if choice_day == "monday" and choice_period == "NO":
 for k, v in monday.items():
   print k, v
于 2013-09-25T19:11:23.860 回答