如何在python中向列表添加元素?
我正在用python完成这项任务,但我不确定是否以正确的方式将元素添加到列表中。因此,基本上我假设创建一个create_list函数,该函数获取列表的大小,并提示用户输入那么多值,然后将每个值存储到列表中。create_list函数应该返回这个新创建的列表。最后,main()函数应该提示用户输入值的数量,将该值传递给create_list函数以设置列表,然后调用get_total函数以打印列表的总数。请告诉我我错过了什么或做错了什么。事先非常感谢你如何在python中向列表添加元素?,python,python-3.x,Python,Python 3.x,我正在用python完成这项任务,但我不确定是否以正确的方式将元素添加到列表中。因此,基本上我假设创建一个create_list函数,该函数获取列表的大小,并提示用户输入那么多值,然后将每个值存储到列表中。create_list函数应该返回这个新创建的列表。最后,main()函数应该提示用户输入值的数量,将该值传递给create_list函数以设置列表,然后调用get_total函数以打印列表的总数。请告诉我我错过了什么或做错了什么。事先非常感谢你 def main(): # creat
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()
必须将输入转换为整数
input()
返回字符串对象。照办
number_of_values = int(input('Please enter number of values: '))
在
main
中,您创建了空列表,但没有将create\u 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()
第一个问题是您没有将
myList
传递到create\u list
函数,因此main中的myList
不会得到更新
如果您想在函数中创建一个列表并返回它,然后获取该列表的总数,您需要首先将该列表存储在某个位置。将输入解析为整数,如果,则始终执行。以下代码应该可以工作并打印正确的结果:)
您需要将create_list()的返回值赋给一个变量,并将其传递到get_total()中
发布解决方案的另一种方法是使用一个函数创建所述列表并查找该列表的总数。在解决方案中,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()
在python中向现有列表中添加元素非常简单。
假设谁有一个名单名字列表1
>>> list1 = ["one" , "two"]
>>> list1 = list1 + "three"
最后一个命令将把元素“三”添加到列表中。这非常简单,因为列表是python中的对象。打印列表1时,您会得到:
["one" , "two" , "three"]
完成您应该使用调用main,如果您认为自己可能做错了什么?您没有给出您认为问题可能是什么,或者当前行为与预期行为有何不同的迹象。“我收到一条错误消息,但不确定原因”,然后将错误消息包含在question@xpng-你没有抓住我们评论的重点。如果您收到一条错误消息,那么您应该将其包含在问题中,以便人们能够更好地帮助您。你所做的就像去看医生说:“请给我药!”但却懒得告诉医生你的耳朵疼。是的,医生可能最终会找出问题所在,但描述你注意到的症状会让事情变得容易得多!同样的事情。@Tadhgmdonald Jensen-我正式将我对这个问题的评论发布到公共领域。请随意复制和粘贴它,使用它修改或修改没有归属。(这可能比试图在这里链接更容易,我不在乎这个类比是否值得称赞。我只是很高兴有人发现它有用!)你的答案非常接近:)。我没有得到更多的错误,但总的来说我得到了0。知道为什么吗?因为myList
应该是create\u list
中的一个全局变量,以便实际修改它。另外,myList
应该在main()
之外声明,或者您可以像在其他答案中一样捕获本地返回值,保留myList
全局变量是另一种实现。TypeError:只能将list(而不是“str”)连接到list
Alex,必须是list1+=[“三”
。但是,使用list1.append(“三”)
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.
>>> list1 = ["one" , "two"]
>>> list1 = list1 + "three"
["one" , "two" , "three"]