在Python中将多个元素添加到列表 [英] Adding multiple elements to a list in Python

查看:1890
本文介绍了在Python中将多个元素添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write something in Python that will be like a piano. Each number that the user enters will play a different sound.


  1. 系统会提示用户输入想要按下的键数(

  2. 系统会提示他们输入一个数字,该声音的次数与输入迭代次数相同。每个数字都是不同的声音。

  3. 它将播放声音。

我正在 userNum 函数遇到麻烦。我需要输入所有数字以将声音添加到列表中,然后另一个函数将读取列表并相应播放每种声音。这就是我到目前为止所拥有的:

I am having trouble with the userNum function. I need all of the numbers that they enter for sounds to append to a list, and then another function will read the list and play each sound accordingly. This is what I have so far:

#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

这是我到目前为止使用的代码的打印清单:

This is what the printed list looks like with the code that I have so far:

>>> 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]

任何想法将其添加到列表中,或者是否有更有效的方法?

Any thoughts of a way to get it to append each number to the list, or if there is a more efficient way of doing this?

推荐答案

第一个您应该在函数中执行的操作是初始化一个空列表。然后,您可以循环正确的次数,并且在 for 循环中,您可以追加 myList 。您还应该避免使用 eval ,在这种情况下,只需使用 int 转换为整数。

The first thing you should do in your function is initialize an empty list. Then you can loop the correct number of times, and within the for loop you can append into myList. You should also avoid using eval and in this case simply use int to convert to an integer.

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]

这篇关于在Python中将多个元素添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆