Python入门:五之 列表、元组、集合

一、列表
(1)创建列表
列表与数组的区别
数组:存储同一数据类型的集合 score = [10,20,30]
列表:可以存储任意数据类型的集合

1>列表里可以存储不同的数据类型

Python入门:五之 列表、元组、集合

2>列表嵌套​​​​​​​

Python入门:五之 列表、元组、集合

(2)列表的特性

 

1>索引

Python入门:五之 列表、元组、集合

2>切片

Python入门:五之 列表、元组、集合

3>重复

Python入门:五之 列表、元组、集合

4>连接

Python入门:五之 列表、元组、集合

5>成员操作符​​​​​​​

Python入门:五之 列表、元组、集合

6>迭代​​​​​​​

Python入门:五之 列表、元组、集合

7>列表里嵌套列表​​​​​​​

Python入门:五之 列表、元组、集合

8>索引​​​​​​​

Python入门:五之 列表、元组、集合

9>切片​​​​​​​

Python入门:五之 列表、元组、集合

来一个练习:

假定有下面的列表:
names = [‘fentiao’,‘fendai’,‘fensi’,‘apple’]
输出结果为: ‘I have fentiao, fendai, fensi and apple.’

Python入门:五之 列表、元组、集合

(3)列表的增加

 

1.>​​​​​​​

Python入门:五之 列表、元组、集合

2>.append:追加 追加一个元素到列表中​​​​​​​

Python入门:五之 列表、元组、集合

3>extend:拉伸 追加多个元素到列表中

Python入门:五之 列表、元组、集合

4>.insert:在指定索引位置插入元素​​​​​​​

Python入门:五之 列表、元组、集合

(4)列表的删除

pop删除后可看到被删除元素,remove删除无法查看被删除元素(彻底删除)​​​​​​​

Python入门:五之 列表、元组、集合

remove:删除指定元素​​​​​​​

Python入门:五之 列表、元组、集合

从内存中删除列表​​​​​​​

Python入门:五之 列表、元组、集合

(5)列表的修改

1>通过索引,重新赋值​​​​​​​

Python入门:五之 列表、元组、集合

2>通过切片​​​​​​​

Python入门:五之 列表、元组、集合

(6)列表的查看

1>查看出现的次数–count​​​​​​​

Python入门:五之 列表、元组、集合

2>查看指定元素的索引值(可以指定索引范围查看)​​​​​​​

Python入门:五之 列表、元组、集合

 

 

************练习,用户登陆**********

题目要求如下:

1.系统里面有多个用户,用户的信息目前保存在列表里面
users = [‘root’,‘westos’]
passwd = [‘123’,‘456’]
2.用户登陆(判断用户登陆是否成功
1).判断用户是否存在
2).如果存在
1).判断用户密码是否正确
如果正确,登陆成功,推出循环
如果密码不正确,重新登陆,总共有三次机会登陆
3).如果用户不存在
重新登陆,总共有三次机会

Python入门:五之 列表、元组、集合

 

 

二、元组

(1)元组的创建
元组(tuple): 元组本身是不可变数据类型,没有增删改查
元组内可以存储任意数据类型​​​​​​​

Python入门:五之 列表、元组、集合

元组里面包含可变数据类型,可以间接修改元组内容​​​​​​​

Python入门:五之 列表、元组、集合

元组里如果只有一个元素的时候,后面要加逗号,否则数据类型不确定​​​​​​​

Python入门:五之 列表、元组、集合

 

(2)元组的特性

1>索引 切片

Python入门:五之 列表、元组、集合

2>重复​​​​​​​

Python入门:五之 列表、元组、集合

3>连接

Python入门:五之 列表、元组、集合

4>成员操作符

Python入门:五之 列表、元组、集合

5>for循环​​​​​​​

Python入门:五之 列表、元组、集合

(3)元组常用方法
count —计算个数
index----索引

Python入门:五之 列表、元组、集合

(4)元组的应用场景
元组的赋值,有多少个元素,就用多少个变量接收

Python入门:五之 列表、元组、集合

三、集合
(1)集合的定义
集合里面的元素是不可重复的

Python入门:五之 列表、元组、集合

(2)集合的特性
###集合只支持 成员操作符 for循环

(3)集合常用方法
s = {6,7,8,9}
1>增加

Python入门:五之 列表、元组、集合

2>删除

Python入门:五之 列表、元组、集合

3>删除指定元素

Python入门:五之 列表、元组、集合
4>交集,并集,差集
 

s1 = {1,2,3}
s2 = {2,3,4}
并集union |
print(‘并集:’,s1.union(s2))
print(‘并集:’,s1|s2)

交集intersection &
print(‘交集:’,s1.intersection(s2))
print(‘交集:’,s1&s2)

差集difference
print(‘差集:’,s1.difference(s2))
print(‘差集:’,s2.difference(s1))

对等差分:并集 - 交集 symmetric_difference
print(‘对等差分:’,s1.symmetric_difference(s2))
print(‘对等差分:’,s2.symmetric_difference(s1))

s3 = {1,2}
s4 = {1,2,3}

print(s4.issuperset(s3))
print(s3.issubset(s4))

两个集合是否不相交 isdisjoint
print(s3.isdisjoint(s4))