【问题标题】:Adding multiple elements to a list in Python在 Python 中将多个元素添加到列表中
【发布时间】:2015-03-07 19:05:05
【问题描述】:

我正在尝试用 Python 编写一些像钢琴一样的东西。用户输入的每个数字都会播放不同的声音。

  1. 系统会提示用户他们希望能够按下多少个键(迭代)。
  2. 他们将被提示输入声音的数字,其次数与他们为迭代输入的次数相同。每个数字都是不同的声音。
  3. 它将播放声音。

userNum 函数有问题。我需要他们为声音输入的所有数字附加到列表中,然后另一个函数将读取列表并相应地播放每个声音。这是我目前所拥有的:

#Gets a user input for each sound and appends to a list.
def userNum(iterations):
  for i in range(iterations):
    a = eval(input("Enter a number for sound: "))
  myList = []
  while True:
    myList.append(a)
    break
  print(myList)
  return myList

这是打印列表与我目前所拥有的代码的样子:

>>> userNum(5)
Enter a number for sound: 1
Enter a number for sound: 2
Enter a number for sound: 3
Enter a number for sound: 4
Enter a number for sound: 5
[5]

任何想法让它将每个数字附加到列表中,或者是否有更有效的方法?

【问题讨论】:

  • 您在for 循环之后 创建列表,然后有一个只运行一次的while 循环。为什么不在for 循环之前 创建列表,并在其中创建append?另外,你应该使用int 而不是eval

标签: python list input append python-3.4


【解决方案1】:

您应该在函数中做的第一件事是初始化一个空列表。然后你可以循环正确的次数,在for循环中你可以append进入myList。您还应该避免使用eval,在这种情况下只需使用int 来转换为整数。

def userNum(iterations):
    myList = []
    for _ in range(iterations):
        value = int(input("Enter a number for sound: "))
        myList.append(value)
    return myList

测试

>>> userNum(5)
Enter a number for sound: 2
Enter a number for sound: 3
Enter a number for sound: 1
Enter a number for sound: 5
Enter a number for sound: 9
[2, 3, 1, 5, 9]

【讨论】:

    【解决方案2】:

    定义用户数(迭代次数):

    number_list = []
    
    while iterations > 0:
        number = int(input("Enter a number for sound : "))
        number_list.append(number)
        iterations = iterations - 1
    return number_list
    

    打印“数字列表 - {0}”.format(userNum(5))

    输入声音的数字:9

    输入声音的数字:1

    输入声音的数字:2

    输入声音的数字:0

    输入声音的数字:5

    数字列表 - [9, 1, 2, 0, 5]

    【讨论】:

      【解决方案3】:

      您可以简单地返回一个列表 comp:

      def userNum(iterations):
          return [int(input("Enter a number for sound: ")) for _ in range(iterations) ]
      

      如果您使用循环,则应使用 while 循环并使用 try/except 验证输入:

      def user_num(iterations):
          my_list = []
          i = 0
          while i < iterations:
              try:
                  inp = int(input("Enter a number for sound: "))
              except ValueError:
                  print("Invalid input")
                  continue
              i += 1
              my_list.append(inp)
          return my_list
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-19
        • 1970-01-01
        • 2016-02-29
        • 2012-09-11
        • 2018-07-29
        • 2020-07-25
        • 2023-04-02
        • 1970-01-01
        相关资源
        最近更新 更多