python中元组,集合的基础知识

本文深入探讨了Python中元组和集合的基本概念及操作方法,包括元组的不可变特性、索引访问、遍历、计数和定位,以及集合的去重、添加、删除、遍历和差集运算。

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

# -*- coding: utf-8 -*-
__author__ = '木之易'
__date__ = '2018/7/23 20:10'

# -------------------元组 tuple
# 元组是一个不可变列表
# 1.声明元组
tuple1 = (1, 2, 3, 4)
# 根据索引取数据
s = tuple1[0]
print(s)
# 元组中的数据不可以进行修改、删除、添加
# TypeError: 'tuple' object does not support item assignment
# tuple1[0] = 123
# TypeError: 'tuple' object doesn't support item deletion
# del  tuple1[0]

# 遍历元组
for x in tuple1:

    print(x)

# 1.count() 函数  统计元素出现次数
result = tuple1.count(1)
print(result)
# 2.index() 函数  获取指定元素的索引
result = tuple1.index(1)
print(result)


#
# ---------------------集合 set
# 集合中没有重复的数据,集合一般用来做去重
# set() 空集合
# set([1,2,3,4])
set1 = set([1, 2, 3, 4, 4, 3, 2, 1])
print(set1)

# add() 添加数据
set1.add(11)
print(set1)

# remove() 删除数据
set1.remove(11)
print(set1)
# 遍历
for x in set1:
    print(x)

set2 = set([5, 3, 7, 1])

# set
# difference() 求差集
set3 = set1 - set2

print(set3)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值