笔记七:python之元组_集合

元组 (tuple)

放数据的一个容器类,与列表相似,也有索引,并且数据也是索引从0开始有序的排列,但是元组是一个不可变的容器,也就是不能对元组里的数据进行增删改查。

可以根据索引取出值

tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1[0])

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
1

Process finished with exit code 0

元组也可以进行切片,切片后得到的也是也是一个元组

tuple1 = (1, 2, 3, 4, 5, 6)
result = tuple1[0:3]
print(result)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
(1, 2, 3)

Process finished with exit code 0

count() 统计元组中某个元素出现的次数

tuple1 = (1, 2, 3, 4, 5, 1, 2, 3, 2, 6)
result = tuple1.count(2)
print(result)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
3

Process finished with exit code 0

index() 获取某个元素在元组中的第一个位置的索引

tuple1 = (1, 2, 3, 4, 5, 1, 2, 3, 2, 6)
result = tuple1.index(3)
print(result)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
2

Process finished with exit code 0

还可以指定查找该元素索引的初识位置及结束位置

tuple1 = (1, 2, 3, 4, 5, 1, 2, 3, 2, 6)
# 参数1:要查找的值  参数2:起始位置  参数3:结束位置
result = tuple1.index(3, 5, 9)
print(result)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
7

Process finished with exit code 0

如果元组中只有一个元素,一定要在末尾加个逗号

tuple1 = (1)
print(tuple1)
tuple2 = (1,)
print(tuple2)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
1
(1,)

Process finished with exit code 0

集合(set)

容器类,可以存储任意类型的数据,与字典类似,字典不可有重复的key,集合中也不会出现重复的数据,所以集合可以用来去重

如果定义的集合有重复的元素,会自动去重!

set1 = {1, 2, 3, 5, 3, 4, 2, 1}
print(set1)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
{1, 2, 3, 4, 5}

Process finished with exit code 0

用remove()函数删除集合里的元素

set1 = {1, 2, 3, 4, 5, 6}
result = set1.remove(4)
print(set1)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
{1, 2, 3, 5, 6}

Process finished with exit code 0

用pop()函数移除函数元素 删除的总是最前面的一个 (集合会自动排序)

set1 = {5, 3, '张三', 6, 1, 7, 8, 'hello'}
print(set1)
result = set1.pop()
print(set1)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
{3, 5, 6, 7, 8, '张三', 'hello'}

Process finished with exit code 0

也可以对集合进行遍历

set1 = {5, 3, '张三', 6, 1, 7, 8, 'hello'}
for s in set1:
    print(s)

结果如下:

D:\Python\Python37\python.exe C:/Users/Administrator/Desktop/小娴python/整理/整理CSDN/笔记四.py
1
3
5
6
7
8
张三
hello

Process finished with exit code 0

上述若有错误,请在评论区指教!谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值