首页 > 解决方案 > 如何为嵌套输入编码并将它们保存到列表中?

问题描述

对不起,伙计们,我还是新手,在这里需要一些帮助。

我正在尝试编写以下代码......由此它将有一个用户输入说:

'选择感兴趣的品牌数量在 1 到 20 之间:'

所以答案的范围可以从 1 到 20,然后根据之前输入的内容,它会抛出输入框来输入将进入列表的项目。

'从以下列表中选择品牌 1:AAA BBB CCC DDD EEE FFF GGG ... LLL'

因此,根据提供的第一个整数,它会抛出“n”个输入框供我输入。然后从 AA 到 LLL 的输入将保存在一个列表中。

我想出了下面的东西,但我有点坚持如何实现它抛出输入框数量供用户输入的部分。

companies = []

while True:
    print('Choose from the below brands or enter nothing to stop')
    brand = input()
    if brand == '':
        break
    companies = companies + [brand]   #list concatenation
print('The companies are:')

for brand in companies:
    print(' ' + brand)

标签: pythonconditional-statements

解决方案


您是否错过了代码的一部分,因为您的代码没有完成您描述的所有事情?

  • 没有输入“在 1 到 20 之间选择感兴趣的品牌数量:”,下面的代码与该数字无关
  • 没有包含从 AAA 到 LLL 品牌的列表

下面是你想要做什么的猜测。如果您提供更多信息,我可能会对其进行编辑。

# get input for number of brands
number_of_brands = int(input("Choose the number of brands interested between 1 to 20:\n"))
# check if the number is between 1 to 20, keep asking input if out of range
while number_of_brands not in range(0,21):
    print("Please choose numbers between 1 to 20.")
    number_of_brands = int(input())

# a list from AAA to LLL
brand_option = [
    "AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH", "III", "JJJ",
    "KKK", "LLL"
    ]

companies = []

# use for loop and range() to get inputs from 1 to 20 times based on input above
for i in range(number_of_brands):
    # string formatting to show current brand number
    brand = input(f"Choose brand {i+1} from the following list:\n{brand_option}\n")
    # check if the brand in option, keep asking input if not in option
    while brand not in brand_option:
        print("Please choose from the following list:")
        brand = input(f"{brand_option}\n")
    # append the brand if in option
    companies.append(brand)

print("The companies are: ")
for brand in companies:
    print(' ' + brand)

旁注:

  • 小写输入是否可以接受,例如 aaa、bbb 和 ccc?

  • 品牌AAA到LLL只有12个品牌,所以如果品牌数量超过12个,结果会重复。

  • 你想要这样的输出吗?

      The companies are:
      brand1: AAA
      brand2: BBB
      brand3: CCC
      brand4: DDD
      brand5: EEE
    

推荐阅读