网站首页 > 基础教程 正文
序列是Python中最基本的数据结构。Python有6种序列类型,但最常见的是列表和元组。列表是最常用的Python数据类型,是用方括号括起来的可变元素序列。
列表可以包含任何数据类型,例如整数、浮点数、字符串和布尔值等。同一个列表还可以包含多种数据类型。
list1=[1, 2, 3, 4]
list2=[1.1, 3.6, 5.8]
list3=[True, False]
list4=['Java', 'Python', 'VB']
list5=[9, 'Python', 3.14]
由于列表是可变的,因此可以向其添加或删除元素。本文将讲解向列表添加元素的多种方法。
1.append()
append()方法可在列表的末尾添加元素。
list1=[1, 2, 3, 4]
list1.append(5)
print(list1)
#输出结果:
[1, 2, 3, 4, 5]
2.insert()
insert()用于将指定元素插入列表的指定位置。
格式:list.insert(index, obj)
参数index指索引号
#将“C++”插入到列表,索引位置为1
list4=['Java', 'Python', 'VB']
list4.insert(1, "C++")
print(list4)
#输出结果:
['Java', 'C++', 'Python', 'VB']
3.extend()
extend()方法用于在列表末尾一次性追加另一个序列中的多个值。可以将元组、集合或字典添加到列表中。
#添加列表
list1=[1, 2, 3, 4]
list1.extend([5,6])
print(list1)
#输出结果:
[1, 2, 3, 4, 5, 6]
#添加元组
list1=[1, 2, 3, 4]
list1.extend(("Python","java"))
print(list1)
#输出结果:
[1, 2, 3, 4, 'Python', 'java']
#将字典添加到列表时只添加键而不是值
list1=[1, 2, 3, 4]
list1.extend({5:"Python",6:"java"})
print(list1)
#输出结果:
[1, 2, 3, 4, 5, 6]
#可以循环遍历字典,使用append方法以元组形式将其添加到列表中
list1=[1, 2, 3, 4]
dict1={5:"Python",6:"java"}
for i, j in dict1.items():
list1.append((i,j))
print(list1)
#输出结果:
[1, 2, 3, 4, (5, 'Python'), (6, 'java')]
#也可以直接把字典添加到列表中
list1=[1, 2, 3, 4]
dict1={5:"Python",6:"java"}
list1.append(dict1)
print(list1)
#输出结果:
[1, 2, 3, 4, {5: 'Python', 6: 'java'}]
在本文中,我们学习了如何使用append()、insert()、extend()方法为列表添加元素。添加的内容不只是单个元素,还可以是列表、元组和字典等。
感谢您的阅读,请关注我,精彩继续!
猜你喜欢
- 2025-03-24 10个非常重要的Python列表方法(python的列表怎么用)
- 2025-03-24 Python编程入门:基本数据类型之列表
- 2025-03-24 python序列之列表详解(python序列类型及运算)
- 2025-03-24 10 非常重要的 Python 列表方法(python 列表常用方法)
- 2025-03-24 Python 基础教程三之Python3 列表
- 2025-03-24 Python的数据结构详解一(列表)(python数据结构教程)
- 2025-03-24 5-4-Python数据类型-列表(python中6种数据类型)
- 2025-03-24 Python 列表:从入门到高阶,避坑 + 性能优化全攻略
- 2025-03-24 python数据容器之列表、元组、字符串
- 2025-03-24 掌握 Python 列表:综合指南(python入门之玩转列表)
- 最近发表
- 标签列表
-
- jsp (69)
- pythonlist (60)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- mysql教程 (60)
- pythonif (86)
- location.href (69)
- deletesql (62)
- c++模板 (62)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)