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

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

问题描述

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

  1. 系统会提示用户输入他们想要按下的按键数量(迭代次数).
  2. 系统会提示他们输入声音的数字,次数与他们输入的迭代次数相同.每个数字都是不同的声音.
  3. 它会播放声音.

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

#获取每个声音的用户输入并附加到列表中.def userNum(迭代次数):对于 i 在范围内(迭代):a = eval(input("请输入声音的数字:"))我的列表 = []而真:myList.append(a)休息打印(我的列表)返回我的列表

这是我目前使用的代码打印出来的列表:

<预><代码>>>>用户数(5)为声音输入一个数字:1输入声音数字:2输入声音数字:3输入声音数字:4输入声音数字:5[5]

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

解决方案

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

def userNum(iterations):我的列表 = []对于 _ 范围内(迭代):value = int(input("请输入声音的数字:"))myList.append(value)返回我的列表

测试

<预><代码>>>>用户数(5)输入声音数字:2输入声音数字:3为声音输入一个数字:1输入声音数字:5输入声音数字:9[2, 3, 1, 5, 9]

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. The user is prompted for how many keys they want to be able to press (iterations).
  2. They will be prompted for a number for a sound the same amount of times as they entered for iterations. Each number is a different sound.
  3. It will play the sounds.

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?

解决方案

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

Testing

>>> 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天全站免登陆