gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:38:51 25 4
gpt4 key购买 nike

我必须编写一段代码来评估我的类(class),我难以完成的要求是将所有房间名称直接从循环中存储到列表或字典中。我已经尝试研究它,但没有什么能真正帮助我具体地做到这一点。由于我是 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'}

如果有更简单的方法,比如使用列表,我也很乐意就此提出任何建议。

最佳答案

你可以使用这样的代码:

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

关于python - 如何在任何循环中永久添加变量或字符串(到列表或字典)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47616188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com