当前位置:首页 > python > 正文内容

如何向python 列表中添加元素

zhangsir4年前 (2022-08-23)python430

Python添加元素有三种方法:append、extend、insert


append:向列表添加元素,添加到尾部

实例:


list=[“my”,“name”,“is”,“mark”,“age”,18]
print(“添加前:”,list)
list.append(“test”)
print(“添加后:”,list)

打印结果:


添加前: [‘my’, ‘name’, ‘is’, ‘mark’, ‘age’, 18]

添加后: [‘my’, ‘name’, ‘is’, ‘mark’, ‘age’, 18, ‘test’]


extend:将另外一个列表的元素逐一添加到指定列表中

实例:


list=[“my”,“name”,“is”,“mark”,“age”,18]
print(“extend前:”,list)
list2=[“A”,“B”]
list.extend(list2)
print(“extend后:”,list)

打印结果:


extend前: [‘my’, ‘name’, ‘is’, ‘mark’, ‘age’, 18]

extend后: [‘my’, ‘name’, ‘is’, ‘mark’, ‘age’, 18, ‘A’, ‘B’]


inset(index,objectA):在指定位置index前面插入对象objectA

实例:


list=[“my”,“name”,“is”,“mark”,“age”,18]
print(“insert前:”,list)
list.insert(3,“test”)
print(“insert后:”,list)

打印结果:


insert前: [‘my’, ‘name’, ‘is’, ‘mark’, ‘age’, 18]

insert后: [‘my’, ‘name’, ‘is’, ‘test’, ‘mark’, ‘age’, 18]


zhangsir版权h8防采集https://mianka.xyz

扫描二维码推送至手机访问。

版权声明:本文由zhangsir or zhangmaam发布,如需转载请注明出处。

本文链接:https://www.mianka.xyz/post/17.html

标签: python
分享给朋友:

“如何向python 列表中添加元素” 的相关文章

在Linux操作系统上使用selenium库

安装selenium模块命令:pip3 install selenium安装chrome命令:yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64....

Python三方库ddddocr实现验证码识别

Python三方库ddddocr实现验证码识别环境要求python >= 3.8安装三方库pip install ddddocr -i https://pypi.tuna.tsinghua.edu.cn/simple参数说明:参数名参数类型默认值说明us...

python selenium find_element_by_xpath 方法已经被弃用的解决办法

背景:在使用最新3.10.4Python版本时候,用selenium进行xpath定位元素,编译器提示:DeprecationWarning:find_element_by_xpath is deprecated. Please use find_element(by=By.XPATH, value...

python 爬虫 报错:UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0x8b in position”解决方案

发现报错“UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1:invalid start byte”,方法一:根据报错提示,错误原因有一条是这样的:“'Accept-Encodi...

python 实现彩色图转素描图

python可以把彩色图片转化为铅笔素描草图,对人像、景色都有很好的效果。而且只需几行代码就可以一键生成,适合批量操作,非常的快捷。需要的第三方库:Opencv - 计算机视觉工具,可以实现多元化的图像视频处理,有Python接口""" Photo ...

python 给电脑设置闹钟

python会自动触发windows桌面通知,提示重要事项,比如说:您已工作两小时,该休息了我们可以设定固定时间提示,比如隔10分钟、1小时等用到的第三方库:win10toast - 用于发送桌面通知的工具from win10toast import ToastNoti...