Python - Python3 列表
1、代码及其说明如下
if __name__ == '__main__':
list1 = ['Google', 'Baidu', 1997, 2000]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
# 通过索引访问
print(list1[0])
# 截取访问,包含头,不包含尾
print(list1[1:3])
# 修改值
list1[2] = 1995
print(list1[2])
# 删除值
del list2[3]
print(list2)
# 获取长度
print(len(list1))
# 拼接
print(list1 + list3)
# 给定重复值
print(['Good'] * 10)
# 判断是否存在
print('Google' in list1)
# 通过下标正向读取
print(list1[1])
# 通过下标反向读取,从-1开始
print(list1[-2])
# 输出某一段
print(list1[1:])
# 创建多维列表
print([list1, list2, list3])
# 获取最大值
print(max(list2))
# 获取最小值
print(min(list2))
# 转成列表
print(list(list1))
# 追加对象
list1.append('Ali')
print(list1)
# 统计某个对象有多少个
list2.append(3)
list2.append(3)
print(list2.count(3))
# 在列表尾部追加新的列表
list1.extend(list3)
print(list1)
# 找出某个值在列表里面的索引位置,只匹配第一个符合条件的
print(list2.index(3))
# 插入数据,如果插在中间,会导致后面的数据下标后移
list1.insert(3, 1996)
print(list1)
# 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list2.pop()
print(list2)
# 移除列表中某个值的第一个匹配项
list2.remove(3)
print(list2)
# 列表取反
list2.reverse()
print(list2)
# 排序,默认正序
list2.sort()
print(list2)
# 复制列表
list4 = list2.copy()
print(list4)
# 清空列表
list2.clear()
print(list2)
输出如下
E:\python_project_path\api_test\venv\Scripts\python.exe "E:\PyCharm\PyCharm 2020.1.2\plugins\python\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 64775 --file E:/python_project_path/api_test/study/for_list.py
pydev debugger: process 8376 is connecting
Connected to pydev debugger (build 201.7846.77)
Google
['Baidu', 1997]
1995
[1, 2, 3, 5]
4
['Google', 'Baidu', 1995, 2000, 'a', 'b', 'c', 'd']
['Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good', 'Good']
True
Baidu
1995
['Baidu', 1995, 2000]
[['Google', 'Baidu', 1995, 2000], [1, 2, 3, 5], ['a', 'b', 'c', 'd']]
5
1
['Google', 'Baidu', 1995, 2000]
['Google', 'Baidu', 1995, 2000, 'Ali']
3
['Google', 'Baidu', 1995, 2000, 'Ali', 'a', 'b', 'c', 'd']
2
['Google', 'Baidu', 1995, 1996, 2000, 'Ali', 'a', 'b', 'c', 'd']
[1, 2, 3, 5, 3]
[1, 2, 5, 3]
[3, 5, 2, 1]
[1, 2, 3, 5]
[1, 2, 3, 5]
[]
Process finished with exit code 0