优秀的编程知识分享平台

网站首页 > 技术文章 正文

Python 3 基础教程 - 列表(python的列表怎么用)

nanyue 2024-09-23 10:50:50 技术文章 6 ℃

Python 中最基本的数据结构是序列。序列的每个元素都分配有一个数字 - 它的位置或索引。第一个索引为0,第二个索引为1,依此类推。

Python 有六种内置类型的序列,但最常见的是列表和元组。

可以对所有序列类型执行某些操作。这些操作包括索引、切片、添加、乘法和检查成员资格。此外,Python 具有用于查找序列长度以及查找其最大和最小元素的内置函数。

访问列表中的值

列表是 Python 中可用的最通用的数据类型,它可以写成方括号之间以逗号分隔的值(项)的列表。关于列表的重要一点是列表中的项目不必是同一类型。创建列表就像在方括号之间放置不同的逗号分隔值一样简单。

要访问列表中的值,请使用方括号与索引一起进行切片以获得该索引处可用的值。例如:

list1 = ['Python', 'Developer',2023];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
print ("list3[-1]: ", list3[-1:])
#运行结果
list1[0]:  Python
list2[1:5]:  [2, 3, 4, 5]
list3[-1]:  ['d']

更新列表

可以通过在赋值运算符的左侧给出切片来更新列表的单个或多个元素,并且可以使用 append() 方法添加到列表中的元素。例如 :

list = ['Python', 'Developer',  2023]
print ("index 2 : ", list[2])

list[2] = 2000
print ("New index 2 : ", list[2])
#运行结果
index 2 :  2023
New index 2 :  2000

删除列表元素

要删除列表元素,如果您确切知道要删除的元素,则可以使用del语句。如果您不确切知道要删除哪些项目,可以使用 remove() 方法。例如 -

现场演示

list = ['Python', 'Developer',  2023]
print (list)

del list[2]
print ("new list : ", list)
#运行结果
['Python', 'Developer', 2023]
new list :  ['Python', 'Developer']

List 基本列表操作

列表对 + 和 * 运算符的响应很像字符串;它们在这里也意味着连接和重复,除了结果是一个新列表,而不是一个字符串。

list1 = ['Java', 'Python', 'Go'] 
list2 = ['C++', 'PHP' ] 
print('len:',len(list1)) 
print('list1+ list2:',list1 + list2) 
print('list2 * 3:', list2 *3)
print('x in list:', 'Java' in list1) 
for x in [1,2,3] : print (x,end = ' ')
# 运行结果
len: 3
list1+ list2: ['Java', 'Python', 'Go', 'C++', 'PHP']
list2 * 3: ['C++', 'PHP', 'C++', 'PHP', 'C++', 'PHP']
x in list: True
1 2 3 

索引、切片和矩阵

由于列表是序列,索引和切片对列表的工作方式与对字符串的工作方式相同。

list1 = ['Java', 'Python', 'Go'] 
print(list1[2])
print(list1[-2])
print(list1[1:])
# 运行结果
Go
Python
['Python', 'Go']

List 内置列表函数和方法

列表函数

len(list) - 返回列表的总长度。

max(list) - 从列表中返回具有最大值的项目。

min(list) - 从列表中返回具有最小值的项目。

list(seq) - 将元组转换为列表。

列表方法

list.append(obj) - 将对象 obj 添加到列表。

list.count(obj) - 返回 obj 在列表中出现的次数。

list.extend(seq) - 将 seq 的内容附加到列表。

list.index(obj) - 返回 obj 出现的列表中的最低索引。

list.insert(index, obj) - 将对象 obj 插入列表中的偏移索引处。

list.pop(obj = list[-1]) - 从列表中删除并返回最后一个对象或 obj。

list.remove(obj) - 从列表中删除对象 obj。

list.reverse() - 反转列表的对象。

list.sort([func]) - 对列表的对象进行排序,如果给定则使用比较函数。

list = ["a", "b", "c", "d"];
obj = 'c'
obj1 = 'e'
list.append(obj)
print(list)
print(list.count(obj))
list.extend(obj1)
print(list)
print(list.index(obj))
list.insert(1,obj1)
print(list)
list.pop()
print(list)
list.remove(obj1)
print(list)
list.reverse()
print(list)
list.sort()
print(list)
list.sort(reverse=True)
print(list)

运行结果:

['a', 'b', 'c', 'd', 'c']
2
['a', 'b', 'c', 'd', 'c', 'e']
2
['a', 'e', 'b', 'c', 'd', 'c', 'e']
['a', 'e', 'b', 'c', 'd', 'c']
['a', 'b', 'c', 'd', 'c']
['c', 'd', 'c', 'b', 'a']
['a', 'b', 'c', 'c', 'd']
['d', 'c', 'c', 'b', 'a']
最近发表
标签列表