定义
[] 内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素
特点
- 可存放多个值
- 按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序
- 可修改指定索引位置对应的值,可变
常用操作命令
增加 操作
每次只能操作一个元素
追加append
append(object, /) method of builtins.list instance
Append object to the end of the list.
a = ["Jack", "Mark"]
a.append("Tom")
print(a) # output: ['Jack', 'Mark', 'Tom']
插入insert
insert(index, object, /) method of builtins.list instance
Insert object before index.
a.insert(1, "Tony")
print(a) # output: ['Jack', 'Tony', 'Mark', 'Tom']
合并extend
将两个列表合并
extend(iterable, /) method of builtins.list instance
Extend list by appending elements from the iterable.
b = [1, 2, 3]
b.extend(a)
print(b) # output: [1, 2, 3, 'Jack', 'Tony', 'Mark', 'Tom']
列表嵌套
[“Jack”, [1,2,“hello”], “Mark”]
b.insert(1,["Hello", "你好"])
print(b) # output: [1, ['Hello', '你好'], 2, 3, 'Jack', 'Tony', 'Mark', 'Tom']
print(b[0], b[1], b[1][1]) # output: 1 ['Hello', '你好'] 你好
删除操作
del
del b[2]
print(b)
删除pop
pop(index=-1, /) method of builtins.list instance
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
a.pop() # 默认删除最后一个元素冰返回被删除的值
a.pop(1) # 指定删除索引为1的值
print(a)
移除remove
(value, /) method of builtins.list instance
Remove first occurrence of value.
b.remove(1)
print(b)
清空clear
clear() method of builtins.list instance
Remove all items from list.
修改操作
names = ["Jack", "Tom", "Jane"]
names[0] = "Mike" # 修改列表中第一个元素值
names[-1] = "Tony" # 修改列表中最后一个元素值
查操作
index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance
Return first index of value.
scores = [20, 30, 40, 50, 40, 30, 30]
scores.index(30) # 返回从左开始匹配到的第一个 30 的值
print(scores)
count(value, /) method of builtins.list instance
Return number of occurrences of value.
scores.count(30) # 统计元素值为 30 的个数
在不知道一个元素在列表哪个位置时
- 先判断是否在列表里 item in list,
- 在的话取索引 item_list=name.index[“eva”],
- 去修改元素值 name[item_list]=“值”
本文介绍了Python中的列表数据结构,包括其定义、特点和常用操作,如append用于在末尾添加元素,insert用于在指定位置插入元素,extend用于合并列表,以及del、pop、remove用于删除元素,还有clear用于清空列表。此外,还提到了如何修改和查找列表中的元素。
4万+

被折叠的 条评论
为什么被折叠?



