python - python 期中考试任务,字典中的列表,列表中的字典

标签 python python-3.x

这是我大学的Python期中考试(第一门课)的任务,我不知道如何完成它。

所以,有一个关于货车、座位名称和可用性的字典(P.S 这个字典要大得多,这只是一个简短的例子)。

d =  {
        'one': [{"Seat_name" : "A1", "isTaken" : False},
             { "Seat_name" : "A2", "isTaken" : True}],
        'two': [{ "Seat_name" : "B1", "isTaken" : True},
             { "Seat_name" : "B2", "isTaken" : False}]
}

我必须向客户提供可用的货车和座位,如果客户手动选择并且座位已被占用或货车已满,我必须提供可用的座位。考试结束后,我仍然找不到解决的方法。因此,任何帮助,将不胜感激。

最佳答案

基本上,这只需要一些dict处理。您可以做的是提取输入字典的“可用座位”部分。然后通过排除给出“不可获得”。剩下的就是一堆 ifprint 语句;由于没有提供详细要求,我将把细节和“美化”留给您。

我自由地将示例字典转换为有效的 Python 语法,并对其进行了一些修改,以便我们可以测试评估的行为。原则上,您还必须检查选择的有效性,例如是否有车厢/座位。我暂时跳过了...

def check_availability(data, choice):
    # get the available seats, let each wagon be a key here as well.
    availability = {}
    for k, v in data.items():
        # k: wagon no., v: dicts specifying seat/availability in the wagon
        # check if all seats are occupied in a wagon
        if not all(i['isTaken'] for i in v):
            # if seats are available, append them to availability dict:
            availability[k] = [i['Seat_name'] for i in v if not i['isTaken']]

    # short version, actually bad style since line too long...
    # availability = {k: [i['Seat_name'] for i in v if not i['isTaken']] for k, v in data.items() if not all(i['isTaken'] for i in v)}

    # now there are three options we can walk through:
    if choice['wagon'] not in availability.keys():
        print(f"wagon {choice['wagon']} is full. available are:\n{availability}")
    elif choice['seat'] not in availability[choice['wagon']]:
        print(f"seat {choice['seat']} is taken. available in wagon {choice['wagon']} are:\n{availability[choice['wagon']]}")
    else:
        print(f"seat {choice['seat']} in wagon {choice['wagon']} is available!")


# testing
d =  {1: [{"Seat_name": "A1", "isTaken": True},
          {"Seat_name": "A2", "isTaken": True}],
      2: [{"Seat_name": "B1", "isTaken": True},
          {"Seat_name": "B2", "isTaken": False},
          {"Seat_name": "B3", "isTaken": False}]}

choice = {'wagon': 1, 'seat': "A1"}
check_availability(d, choice)
# wagon 1 is full. available are:
# {2: ['B2', 'B3']}

choice = {'wagon': 2, 'seat': "B1"}
check_availability(d, choice)
# seat B1 is taken. available in wagon 2 are:
# ['B2', 'B3']

choice = {'wagon': 2, 'seat': "B2"}
check_availability(d, choice)
# seat B2 in wagon 2 is available!

关于python - python 期中考试任务,字典中的列表,列表中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58911315/

相关文章:

python - 在我的 Flask 应用程序中使用 "BOTO"出现 Amazon S3 文件上传问题 -Python

python - 无法让验证码出现

python - "if"语句不适用于输入变量

python-3.x - 使用 ALSA 在 RaspBerry Pi 4+ 上使用 PyGame 的音频 cdrom 没有声音

python - 如何在 Xlsxwriter 中锁定滚动?

python - 如何使用Python将 "Microsoft Excel Object"VBA代码添加到Excel文件

python - Tornado:从部分 URL 创建完整 URL

python - 当我将存档导入其他代码时,Tkinter Entry 为 0

python - Python 3.x 中的 `__rdiv__()` 和 `__idiv__` 运算符是否已更改?

python - 暂停主进程直到派生进程开始执行?