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

时间:2016-02-13 18:10:26

标签: python list append key

它有效,但如何为键添加多个值? 这是我的代码:

    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']]

或者那些东西。感谢。

1 个答案:

答案 0 :(得分:1)

您必须使用字典代替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)

在这种情况下,检查room_name中是否存在dimention,如果不是room_name作为关键字,请指定wall_area的第一个值;否则将wall_area附加到现有的room_name列表中。    您也可以使用set代替dictionary