【问题标题】:write a program to store seven fruits in a list entered by the user编写一个程序,将七个水果存储在用户输入的列表中
【发布时间】:2022-12-31 20:16:47
【问题描述】:
a = input("Name of 1st Fruit:  ")
b = input("Name of 2nd Fruit:  ")
c = input("Name of 3rd Fruit:  ")
d = input("Name of 4th Fruit:  ")
e = input("Name of 5th Fruit:  ")
f = input("Name of 6th Fruit:  ")

l = (a,b,c,d,e,f)
print(l)

编写一个程序,将七个水果存储在用户输入的列表中... 这里我们使用输入函数来输入七个水果的名称,我们必须将这些名称存储在一个列表中。 在那之后,我们必须做什么?

【问题讨论】:

  • 您将它们存储在元组中,而不是列表中。
  • 您可以使用循环将每个添加到列表中,不要创建 7 个变量

标签: python coding-style python-3.10


【解决方案1】:

正如@azro 在 cmets 中提到的,最好将 at store 直接循环到列表中,而不是创建 7 个不同的变量,例如:

fruits = []
for i in range(1,8):
    fruits.append(input(f"Name of Fruit {i}:  "))
print(fruits)

结果:

Name of Fruit 1:  Melon
Name of Fruit 2:  Apple
Name of Fruit 3:  Orange
Name of Fruit 4:  Banana
Name of Fruit 5:  Citrus
Name of Fruit 6:  Plum
Name of Fruit 7:  Mandarin
['Melon', 'Apple', 'Orange', 'Banana', 'Citrus', 'Plum', 'Mandarin']

【讨论】:

    【解决方案2】:

    您可以使用 for 循环来避免重复代码。 append 方法会将每个水果添加到水果列表中。

    fruits = []
    for i in range(7):
        fruit = input("Name of Fruit:  ")
        fruits.append(fruit)
    
    print(fruits)
    

    【讨论】:

      【解决方案3】:
      list = []
      v = ["1st", '2nd', '3rd', '4th', '5th', '6th', '7th']
      for i in v:
          a = input("Enter name of " + v[i]+"fruit:")
          list.append(a)
      print(list)
      

      你应该在for循环和append的帮助下直接将它存储在列表中,我按照你的需要做了它。

      【讨论】:

        【解决方案4】:

        这是一个使用列表理解的简单单行代码。

        fruits = [input(f'Enter Fruit {x} 
        ') for x in range(1, 8)]
        

        【讨论】:

          猜你喜欢
          • 2018-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多