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

How to add elements to a List in python?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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()


main中,您创建了一个空列表,但没有为其分配create_list结果。另外,您应该将用户输入强制转换为int

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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()


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

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

并希望将每个输入用作整数。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    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()

第一个问题是您没有将myList传递给create_list函数,因此main内部的myList不会得到更新。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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()

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

1
2
3
4
5
myList = create_list()
total = get_total(myList)

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

在python中将元素添加到现有列表很简单。
假设谁拥有列表名称list1

1
2
3
>>> list1 = ["one" ,"two"]

>>> list1 = list1 +"three"

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

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

完成了