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

2024-04-20 13:55:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须为课程的评估写一段代码,我很难完成的要求是直接从循环中将所有房间名称存储到列表或字典中。我试过研究它,但没有什么能真正帮助我做到这一点。由于我对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'}

如果有一个更简单的方法,比如使用一个列表,我也很乐意得到任何建议。你知道吗


Tags: thename名称number列表forinputroom
3条回答

像这样的事情会有用的:

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

下面是检查有效输入的较长代码:

#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")

您可以使用如下代码:

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)}

相关问题 更多 >