如何为嵌套输入编码并将其保存到列表中?

2024-10-02 04:23:55 发布

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

对不起,伙计们,我还是新来的,想在这里得到一些帮助

我正在尝试编写以下代码。。。它将有一个用户输入,表示:

“选择感兴趣的品牌数量,介于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)

Tags: 项目答案代码用户内容列表数量感兴趣
2条回答

首先,我很困惑。我猜你想要的第一部分如下

假设你已经准备好了你的品牌清单

brands = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG"]
companies = []

while True:
    print (brands)
    print('Choose from the above brands or enter nothing to stop')
    brandindex = input()
    if brandindex == '':
        break
    else:
        companies.append(brands[int(brandindex)])
print (companies)

如果我输入索引1,2&;3、以下内容将从“公司”列表中打印出来

['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG']
Choose from the above brands or enter nothing to stop
1
['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG']
Choose from the above brands or enter nothing to stop
2
['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG']
Choose from the above brands or enter nothing to stop
3
['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG']
Choose from the above brands or enter nothing to stop

['BBB', 'CCC', 'DDD']

这是我对第一部分的猜测。我不太明白你为什么要在之后马上打印brand in companies?从这个方向纠正我

由于代码没有完成您描述的所有功能,您是否遗漏了代码的一部分

  • “选择感兴趣的品牌数量在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
    

相关问题 更多 >

    热门问题