如何将多个键附加到列表中的值?

How do you append multiple keys to a value in a list?

它可以工作,但我如何向一个键添加多个值? 这是我的代码:

    for x in range(number_of_wall):
        wall = 1
        wall_area = input("What is the area of wall {}" .format(wall) + " in " + room_name + ": ")
        dimention.append([room_name, wall_area])
        wall = wall + 1    
    print(dimention)

这就是它的结果:

[['Lounge', '13'], ['Lounge', '13'], ['Lounge', '13'], ['Lounge', '13'], ['Bedroom', '14'], ['Bedroom', '14'], ['Bedroom', '14'], ['Bedroom', '14']]

我怎样才能修改我的代码,使其出现:

[['Lounge': '13', '13', '13', '13'], ['Bedroom': '14', '14', '14', '14']]

或者类似的东西。谢谢

您必须使用字典代替 dimention 的列表:

dimention = {}
for x in range(number_of_wall):
    wall = 1
    wall_area = input("What is the area of wall {}" .format(wall) + " in " + room_name + ": ")
    if room_name not in dimention:
        dimention[room_name] = [wall_area]
    else:
        dimention[room_name].append(wall_area)
    wall = wall + 1    
print(dimention)

在这种情况下,检查 dimention 中是否存在 room_name 如果不添加 room_name 作为键并分配 wall_area 的第一个值;否则将 wall_area 附加到现有的 room_name 列表。 您也可以使用 set 而不是 dictionary.