如何在python中向列表添加元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36108824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:25:51  来源:igfitidea点击:

How to add elements to a List in python?

pythonpython-3.x

提问by HenryDev

I'm working on this task in python, but I'm not sure if I'm adding the elements to a list the right way. So basically I'm suppose to create a create_list function the takes the size of the list and prompt the user for that many values and store each value into the list. The create_list function should return this newly created list. Finally the main() function should prompt the user for the number of values to be entered, pass that value to the create_list function to set up the list, and then call the get_total function to print the total of the list. Please tell me what I'm missing or doing wrong. Thank you so much in advance.

我正在用 python 处理这个任务,但我不确定我是否以正确的方式将元素添加到列表中。所以基本上我假设创建一个 create_list 函数,它采用列表的大小并提示用户输入那么多值并将每个值存储到列表中。create_list 函数应该返回这个新创建的列表。最后,main() 函数应提示用户输入要输入的值的数量,将该值传递给 create_list 函数以设置列表,然后调用 get_total 函数以打印列表的总数。请告诉我我错过了什么或做错了什么。非常感谢你。

def main():
    # create a list
    myList = []

    number_of_values = input('Please enter number of values: ')

    # Display the total of the list  elements.
    print('the list is: ', create_list(number_of_values))
    print('the total is ', get_total(myList))

    # The get_total function accepts a list as an
    # argument returns the total sum of the values in
    # the list

def get_total(value_list):

    total = 0

    # calculate the total of the list elements
    for num in value_list:
        total += num

    #Return the total.
    return total

def create_list(number_of_values):

    myList = []
    for num in range(number_of_values):
        num = input('Please enter number: ')
        myList.append(num)

    return myList

main()

回答by Mikhail Gerasimov

In mainyou created empty list, but didn't assign create_listresult to it. Also you should cast user input to int:

main您创建空列表中,但没有为其分配create_list结果。您还应该将用户输入转换为int

def main():
    number_of_values = int(input('Please enter number of values: '))  # int

    myList = create_list(number_of_values)  # myList = function result
    total = get_total(myList)

    print('the list is: ', myList)
    print('the total is ', total)

def get_total(value_list):
    total = 0
    for num in value_list:
        total += num
    return total

def create_list(number_of_values):
    myList = []
    for _ in range(number_of_values):  # no need to use num in loop here
        num = int(input('Please enter number: '))  # int
        myList.append(num)
    return myList

if __name__ == '__main__':  # it's better to add this line as suggested
    main()

回答by Mr. E

You must convert inputs to integer. input()returns a string object. Just do

您必须将输入转换为整数。input()返回一个字符串对象。做就是了

number_of_values = int(input('Please enter number of values: '))

And with every input you want to use as integer.

并且对于您要用作整数的每个输入。

回答by Namit Singal

First Problem is you are not passing myListto create_listfunction, so myListinside of main is not going to get updated.

第一个问题是你没有传递myListcreate_list函数,所以myListmain 内部不会得到更新。

If you want to create a list inside the function and return it, and then get a total for that list, you need to first store the list somewhere. parse the inputs as integer, also, always do if __name__ == '__main__':. The Following code should work and print the correct result :)

如果您想在函数内部创建一个列表并返回它,然后获得该列表的总数,您需要首先将列表存储在某处。将输入解析为整数,也总是 do if __name__ == '__main__':。以下代码应该可以工作并打印正确的结果:)

def main():
    number_of_values = int(input('Please enter number of values: '))
    myList = create_list(number_of_values)
    print('the list is: ', myList)
    print('the total is ', get_total(myList))

def get_total(value_list):
    total = 0
    for num in value_list:
        total += num
    return total

def create_list(number_of_values):
    myList = []
    for num in range(number_of_values):
        num = int(input('Please enter number: '))
        myList.append(num)
    return myList
if __name__ == '__main__':
    main()

回答by Mark Babatunde

An alternative method to the posted solutions could be to have one function that creates your said list and finds the total of that list. In the solution, the map function goes through all the values given to it and only keeps the integers (The split method is used to remove commas and spaces from the values). This solution will print your list and values, but will not return any said value, so it will produce a NoneType, if you were to examine the function at the end.

已发布解决方案的另一种方法可能是使用一个函数来创建您所说的列表并找到该列表的总数。在解决方案中,map 函数遍历所有给它的值,只保留整数(split 方法用于从值中删除逗号和空格)。此解决方案将打印您的列表和值,但不会返回任何所述值,因此如果您在最后检查该函数,它将生成一个 NoneType。

    def main():
        aListAndTotal()

        #Creates list through finding the integers and removing the commas
        #For loop iterates through list and finds the total
        #Does not return a value, but prints what's stored in the variables

    def aListAndTotal():
        myList = map(int, input("Please enter number of values: ").split(","))
        total = 0
        for num in myList:
            total += num
        print ("The list is: ", myList)
        print ("The total is: ", total)

    if __name__ == "__main__":
        main()

回答by Akhil Rao

List is one of the most important data structure in python where you can add any type of element to the list.

a=[1,"abc",3.26,'d']

To add an element to the list, we can use 3 built in functions:
a) insert(index,object)
This method can be used to insert the object at the preferred index position.For eg, to add an element '20' at the index 1:
     a.index(1,20)
Now , a=[1,20,'abc',3.26,'d']

b)append(object)
This will add the object at the end of the list.For eg, to add an element "python" at the end of the list:
    a.append("python")
Now, a=[1,20,'abc',3.26,'d','python']

c)extend(object/s)
This is used to add the object or objects to the end of the list.For eg, to add a tuple of elements to the end of the list:
b=(1.2, 3.4, 4.5)
a.extend(b)
Now , a=[1,20,'abc',3.26,'d','python',1.2, 3.4, 4.5]

If in the above case , instead of using extend, append is used ,then:
a.append(b)
Now , a=[1,20,'abc',3.26,'d','python',(1.2, 3.4, 4.5)]
Because append takes only one object as argument and it considers the above tuple to be a single argument that needs to be appended to the end of the list.

回答by Phuo

You need to assign the return value of create_list() to a variable and pass that into get_total()

您需要将 create_list() 的返回值分配给一个变量并将其传递给 get_total()

myList = create_list()
total = get_total(myList)

print("list " + str(myList))
print("total " + str(total))

回答by Alex

Adding an element to an existing list in python is trivial. Assume who have a list names list1

将元素添加到 python 中的现有列表是微不足道的。假设谁有一个列表名称 list1

>>> list1 = ["one" , "two"]

>>> list1 = list1 + "three"

this last command will add the element "three" to the list. This is really simple, because lists are objects in python. When you print list1 you get:

最后一条命令会将元素“three”添加到列表中。这真的很简单,因为列表是 Python 中的对象。当您打印 list1 时,您会得到:

["one" , "two" , "three"]

Done

完毕