编程语言
首页 > 编程语言> > python如何向列表中追加元素

python如何向列表中追加元素

作者:互联网

append()方法
作用:append() 方法用于在列表末尾添加新的对象。该方法无返回值,但是会修改原来的列表。

场景:该方法可以用于在循环迭代过程中保存每一次的运行结果,比如为了画图,保存逻辑回归过程中每一次迭代的代价函数结果值。

定义空列表

costs = []

for i in range(10):
#在代价函数2列表末尾添加新的值
costs.append(i)
#显示每次添加新对象后的列表
print("costs = " + str(costs))
1
2
3
4
5
6
7
8
costs = [0]
costs = [0, 1]
costs = [0, 1, 2]
costs = [0, 1, 2, 3]
costs = [0, 1, 2, 3, 4]
costs = [0, 1, 2, 3, 4, 5]
costs = [0, 1, 2, 3, 4, 5, 6]
costs = [0, 1, 2, 3, 4, 5, 6, 7]
costs = [0, 1, 2, 3, 4, 5, 6, 7, 8]
costs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
————————————————
3 examples to append list in python

标签:迭代,python,列表,costs,追加,添加,append
来源: https://www.cnblogs.com/tcpdump-examples/p/15758361.html