关注分享主机优惠活动
国内外VPS云服务器

python如何向空列表添加数据

可以使用append()方法向空列表中添加数据。例如:

My_list = [] #创建一个空列表
My_list.append(10) #将整数10添加到列表中。
My_list.append('hello') #向列表中添加字符串' hello '。
My_list.append([1,2,3]) #将列表[1,2,3]添加到列表中。
Print(my_list) # Output: [10,' hello ',[1,2,3]]除了append()方法,还可以使用insert()方法在指定位置插入数据。例如:

我的列表= []
My_list.insert(0,' first') #在索引位置0插入字符串' first '。
My_list.insert(2,' third') #在索引位置2插入字符串' third '。
Print(my_list) # output: ['first ',' third']需要注意的是,使用append()方法添加数据会直接将数据添加到列表的末尾,而使用insert()方法可以指定插入位置。

以上内容来自互联网,不代表本站全部观点!欢迎关注我们:zhujipindao。com

未经允许不得转载:主机频道 » python如何向空列表添加数据

评论 抢沙发

评论前必须登录!