Python学习笔记(7)-元组

1、元组的定义

Python的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

  1.  tuple1 = ()  # 定义一个空元组
     print(tuple1)  # ()
    
  2. (1)和(1)python既可以认为是int类型的数字1,也可以认为是一个元素的元组。
    所以在定义只含有一个元素的元组,一个元素也要在后面加上逗号,这样python编译器才会识别为元组

    print(type(1))  # <class 'int'>
    tuple2 = (1,) 
    print(type(tuple2))  # <class 'tuple'>
    
  3. 多个元素的元组

    tuple3 = (1, 2, 3)  # 定义含有多个元素的元组
    print(tuple3)  # (1, 2, 3)
    

2、元组元素的访问

通过索引下标来访问元组中的元素

tuple4 = ("a", "b", "c")
print(tuple4[0])  # a
print(tuple4[0:])  # ('a', 'b', 'c')
print(tuple4[0:2])  # ('a', 'b')

3、元素的修改

从之前的定义知道元组的元素是不能修改的,所以元组的修改只能通过重新赋值的方式。

tuple5 = ('nice', 'to', 'meet', 'you')
print(tuple5)  # ('nice', 'to', 'meet', 'you')

#元组的元素不允许修改
#tuple5[0]='a' TypeError: 'tuple' object does not support item assignment

tuple5 = ('hello','every','body')
print(tuple5)  # ('hello', 'every', 'body')

4、元组的删除

元组的元素时不允许删除的,只能使用del语句删除整个元组

tuple6 = (1,'5','a')
print(tuple6)  # (1, '5', 'a')
del tuple6 # 删除元组tuple6

# NameError: name 'tuple6' is not defined
#print("删除后的tuple6:"+tuple6)

5、元组的表达式

Pyhton表达式结果描述
len((1, 5, 654, 6, 54))5len()方法可以获取元组长度
(1, 2, 3)+(4, 5, 6)(1, 2, 3, 4, 5, 6)合并元组
(‘hello’, )*3(‘hello’, ‘hello’, ‘hello’)将元组重复整数倍
3 in (1, 2, 3)True元素是否存在于元组中
4 not in (1, 2, 3)True元素是否不存在于元组中
for x in (1, 2, 3):print(x)1 2 3迭代遍历元组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值