本文涉及内容为阿里云天池学习中心python训练营课程,部分内容摘自课程课件,剩余部分来自编者理解与网络搜索补充算是训练营课程的部分内容精简版,若有问题或错误欢迎留言,如有侵权和冒犯可联系删除。
一. 列表
简介:列表是有序集合,没有固定大小,能够保存任意数量任意类型的 Python 对象,语法为 [元素1, 元素2, ..., 元素n]
。其常用数据类型为:
- 整型
<class 'int'>
- 浮点型
<class 'float'>
- 布尔型
<class 'bool'>
- 列表
<class 'list'>
- 元组
<class 'tuple'>
- 字典
<class 'dict'>
- 集合
<class 'set'>
- 字符串
<class 'str'>
1.创建列表。用逗号分隔的不同的元素分隔开,再使用中括号将元素捆绑在一起。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x, type(x))
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>
利用range()
创建列表:
x = list(range(10))
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
x = list(range(1, 11, 2))
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>
x = list(range(10, 1, -2))
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
[1, 3, 5, 7, 9] <class 'list'>
[10, 8, 6, 4, 2] <class 'list'>
同时:由于list的元素可以是任何对象,因此列表中所保存的是对象的指针。即使保存一个简单的[1,2,3]
,也有3个指针和3个整数对象。
创建一个混合列表:
mix = [1, 'lsgo', 3.14, [1, 2, 3]]
print(mix, type(mix))
# [1, 'lsgo', 3.14, [1, 2, 3]] <class 'list'>
[1, 'lsgo', 3.14, [1, 2, 3]] <class 'list'>
2.常用的python列表操作的函数和方法:
1、cmp(list1, list2):比较两个列表的元素 (python3已丢弃) 3
2、len(list):列表元素个数 4
3、max(list):返回列表元素最大值 5
4、min(list):返回列表元素最小值 6 5、list(seq):将元组转换为列表
5、list.append(obj):在列表末尾添加新的对象 3