如何在任何循环中永久添加变量或字符串(到列表或字典)?

时间:2017-12-03 07:19:37

标签: python list dictionary

我必须编写一段代码来评估我的课程,我要求完成的困难是将所有房间名称直接存储在一个列表或字典中。我试过研究它,但没有什么能真正帮助我做到这一点。因为我对python很陌生,所以我真的很感激能够以更简单的方式解决这个问题。

这是我的代码:

print ("+++++++++++++++\nPRICE ESTIMATOR\n+++++++++++++++")

roomnames={}
cnumber = input("Please enter your customer number: ").upper()

dateofestimate = input("Please enter the estimated date (in the format dd/mm/yyyy) : ")

rooms = int(input("Please enter the number of rooms you would like to paint: "))

x = 0 

for i in range (0,rooms):
    x = x+1
    print("\nFOR ROOM:", str(x))
    Rname = input("Please enter a name: ")
    roomnames = {(x):(Rname)}

print(roomnames)

我得到的输出是这样的:

FOR ROOM: 1
Please enter a name: lounge

FOR ROOM: 2
Please enter a name: kitchen

FOR ROOM: 3
Please enter a name: bedroom 1 

FOR ROOM: 4
Please enter a name: bedroom 2

{4: 'bedroom 2'}

我想存储所有房间名称及其对应的房间号码,以获得类似的内容:

{1: 'lounge', 2: 'kitchen', 3: 'bedroom 1', 4: 'bedroom 2'}

如果有一种更简单的方法,比如使用清单,我也很乐意提供任何建议。

3 个答案:

答案 0 :(得分:3)

你可以使用这样的代码:

rooms = int(input("Please enter the number of rooms you would like to paint: "))
roomandname= {i: input("Please enter a name: ") for i in range(rooms)}

答案 1 :(得分:1)

这样的事情可行:

RoomsNumberAndName.append(x)
Rname = input("Please enter a name: ")
RoomsNumberAndName.append(Rname)

答案 2 :(得分:1)

这是一个更长的代码,用于检查有效输入:

#Let's first find nr (nr of rooms)
valid_nr_rooms = [str(i) for i in range(1,11)] #1-10
while True:
    nr = input("Please enter the number of rooms you would like to paint (1-10): ")
    if nr in valid_nr_rooms:
        nr = int(nr)
        break
    else:
        print("Invalid input")

#Now let's create a the dict
#But we could also use a list if the keys are integers!
rooms = {}
for i in range(nr):
    while True:      
        name = input("Name of the room: ").lower()
        # This checks if string only contains 1 word
        # We could check if there are digits inside the word etc etc
        if len(name.split()) == 1:
            rooms[i] = name
            break
        else:
            print("Invalid input")