它有效,但如何为键添加多个值? 这是我的代码:
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']]
或者那些东西。感谢。
答案 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
。