python--列表、元组、集合

本文详细介绍了Python中的三种重要数据结构——列表、元组和集合。列表作为可变数据类型,支持多种操作如索引、切片、添加、删除和修改。元组是不可变数据类型,可用于间接修改其包含的可变元素。集合则提供了不重复元素的存储,支持交集、并集、差集等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

li = [1,1.2,'hello',True]
print(li)
print(type(li))

2>列表嵌套

li1 = [1,1.2,'hello',True,[1,2,3,4,5]]
print(li1)
print(type(li1))

(2)列表的特性
1>索引

service = ['http','ssh','ftp','dns']
 print(service[0])#输出第0个值(列表从0开始)
 print(service[-1])#逆序输出

2>切片

print(service[1:])#输出第一个值后面的所有值
 print(service[:-1])#输出最后一个值
print(service[::-1])#逆序输出

3>重复

print(service * 3)

4>连接

service1 = ['mysql','firewalld']
 print(service + service1)

5>成员操作符

 print('mysql' in service)
print('mysql' in service1)

6>迭代

 print('显示所有服务'.center(50,'*'))
for se in service:
print(se)

7>列表里嵌套列表

service2 = [['http',80],['ssh',22],['ftp',21]]

8>索引

print(service2[0][1])
print(service2[-1][1])

9>切片

print(service2[:][1])
print(service2[:-1][0])
print(service2[0][:-1])

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

names = ['fentiao','fendai','fensi','apple']
print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1])

(3)列表的增加
1.>

 print(service + ['firewalld'])

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

service.append('firewalld')
print(service)

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

service.extend(['mysql','firewalld'])
 print(service)

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

service.insert(1,'samba')
print(service)

(3)列表的删除
pop删除后可看到被删除元素,remove删除无法查看被删除元素(彻底删除)

In [19]: service = ['http','ssh','ftp','dns']                           

In [20]: service.pop()                                                  
Out[20]: 'dns'

In [21]: service                                                        
Out[21]: ['http', 'ssh', 'ftp']

In [22]: a = service.pop()                                              

In [23]: service                                                        
Out[23]: ['http', 'ssh']

remove:删除指定元素

In [30]: service = ['http','ssh','ftp','dns']                           
In [31]: a = service.remove('ssh')                                      

In [32]: print(service)                                                 
['http', 'ftp', 'dns']

In [33]: print(a)                                                       
None

In [34]: print(service)                                                 
['http', 'ftp', 'dns']

从内存中删除列表

In [35]: del service                                                    

In [36]: print(service)    

(4)列表的修改
1>通过索引,重新赋值

service = ['http','ssh','ftp','dns']
service[0] = 'mysql'
print(service)

2>通过切片

service = ['http','ssh','ftp','dns']
print(service[:2])
service[:2] = ['samba','nfs']
print(service)

(5)列表的查看
1>查看出现的次数–count

service = ['ftp','ssh','ftp','dns']
print(service.count('ftp'))
print(service.count('dns'))

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

service = ['ftp','ssh','ftp','dns']
print(service.index('ssh'))
print(service.index('ftp',1,4))

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


users = ['root','westos']
passwords = ['123','456']

#尝试登录次数
trycount = 0

while trycount < 3:
    inuser = input('用户名: ')
    inpassword = input('密码: ')

    trycount += 1

    if inuser in users:
        index = users.index(inuser)
        password = passwords[index]

        if inpassword == password:
            print('%s登录成功' %(inuser))
            break
        else:
            print('%s登录失败 : 密码错误' %inuser)
    else:
        print('用户%s不存在' %inuser)
else:
    print('尝试超过三次,请稍后再试')

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

t = (1,2.3,True,'star')
print(t)
print(type(t))

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

t1 = ([1,2,3],4)
t1[0].append(4)
print(t1)

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

t2 = ('hello',)
print(type(t2))

(2)元组的特性

1>索引 切片

allowusers = ('root','westos','redhat')
allowpasswd = ('123','456','789')
print(allowusers[0])# 输出第0个字符
print(allowusers[-1])#输出最后一个
print(allowusers[1:])#从第一个开始输出
print(allowusers[:-1])
print(allowusers[::-1])#逆序输出

2>重复

 print(allowusers * 3)

3>连接

print(allowusers + ('linux','python'))

4>成员操作符

print('westos' in allowusers)
print('westos' not in allowusers)

5>for循环

 for user in allowusers:
print(user)
   for index,user in enumerate(allowusers):
        print('第%d个白名单用户: %s' %(index+1,user))
for user,passwd in zip(allowusers,allowpasswd):
    print(user,':',passwd)

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

t = (1,2.3,True,'linux')

print(t.count('linux'))
print(t.index(1))

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

 t = ('westos',11,100)
name,age,score = t
print(name,age,score)

scores = (100,89,45,78,65)

scoresLi = list(scores)
scoresLi.sort()
print(scoresLi)
scores = sorted(scores)
print(scores)

minscore,*middlescore,maxscore = scores
print(minscore)
print(middlescore)
print(maxscore)

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

s = {1,2,3,1,2,3,4,5}
s1 = {1}
 s3 = set([])
li = [1,2,3,1,2,3]
print(set(li))

(2)集合的特性
集合只支持 成员操作符 for循环
(3)集合常用方法
s = {6,7,8,9}
1>增加

s.add(1)
s.update({2,3,5})

2>删除

 s.pop()

3>删除指定元素

s.remove(9)

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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值