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

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

如果有一个更简单的方法,就像使用一个列表我很乐意提供任何关于tha也是。

回答:

这是一个较长的代码检查有效输入:

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

回答:

一些像这样的事情会工作:

RoomsNumberAndName.append(x) 

Rname = input("Please enter a name: ")

RoomsNumberAndName.append(Rname)

回答:

你可以使用这样的代码:

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

以上是 如何在任何循环中永久添加变量或字符串(到列表或字典)? 的全部内容, 来源链接: utcz.com/qa/259871.html

回到顶部