簡體   English   中英

如何在python中向List添加元素?

[英]How to add elements to a List in python?

我正在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()

main您創建了空列表,但沒有為其分配create_list結果。 您還應該將用戶輸入intint

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()返回一個字符串對象。 做就是了

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

並且每個輸入都要用作整數。

第一個問題是你沒有將myList傳遞給create_list函數,因此myList不會更新。

如果要在函數內部創建一個列表並將其返回,然后獲取該列表的總計,則需要先將列表存儲在某處。 將輸入解析為整數, if __name__ == '__main__': ,也總是這樣做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()

發布解決方案的另一種方法可能是創建一個函數來創建所述列表並查找該列表的總和。 在解決方案中,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()

您需要將create_list()的返回值賦給變量並將其傳遞給get_total()

myList = create_list()
total = get_total(myList)

print("list " + str(myList))
print("total " + str(total))
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.

在python中將元素添加到現有列表是微不足道的。 假設誰有一個列表名列表1

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

>>> list1 = list1 + "three"

最后一個命令會將元素“three”添加到列表中。 這很簡單,因為列表是python中的對象。 當你打印list1時,你得到:

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

完成

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM