前面我们学习了python常用的数据类型,运算符,学习数据类型有助于我们更好的表达数据和处理数据;数据结构则是为了更好的安排数据,可以通过数据结构将现实生活中复杂的情况简化并进行抽象表
数据结构是通过某种方式组织在一起的数据元素的集合,这些数据元素可以是数字或字符,甚至可以是其他数据结构;
创建列表
直接用“=”创建列表,给变量赋值:
team=('Lily','Jack','Tom')
print (team)
>>>>
('Lily', 'Jack', 'Tom')
获取列表值
用索引来访问list中每一个位置的元素,记得索引是从0开始的;
| 列表项 |
“Lily” |
"Jack" |
"Tom" |
| 索引值 |
0 |
1 |
2 |
team=['Lily','Jack','Tom']
print (team[0])
print (team[1])
print (team[2])
print (team[3])
>>>>
Lily
Jack
Tom
IndexError: list index out of range #当索引超出了范围时,
Python会报一个IndexError错误,所以,要确保索引不要越界
用len()函数可以获得list元素的个数:
print (len(team))
>>> 3
print (team[-1])
>>> Tom
修改列表
team[1]="Kate"
print (team)
>>> ['Lily', 'Kate', 'Tom']
team.append("Sam")
print (team)
>>>['Lily', 'Kate', 'Tom', 'Sam']
或把元素插入到指定位置
team.insert(0, 'Fanny')
print (team)
>>> ['Fanny', 'Kate', 'Tom','Sam']
删除列表
用pop(i)来删除列表的某个元素,其中i是索引位置,要删除list末尾的元素,直接用pop();
team.pop(2)
print (team)
>>> ['Fanny', 'Kate','Sam']
当不再使用时,使用del命令删除整个列表
team=['Lily','Jack','Tom']
del team
print (team)
>>>
NameError: name 'team' is not defined
其他介绍
>>> T = ['ok',Ture,333]
>>> team = ['Lily','Jack', ['111', '323'], 'Tom']

1.回复“PY”领取1GB Python数据分析资料
2.回复“BG”领取5GB 名企数据分析报告

