03元祖

1.创建和访问一个元祖,元祖不可改变,不可以任意修改,
元祖的内容不可以修改(列表可任意修改、删除),
创建一个元祖使用大部分使用(),如下
>>>temp = (1, 2, 3, 4)
>>>temp
>>>(1, 2, 3, 4)
>>>type(temp)
>>><class 'tuple'>#元祖
>>>
>>>temp(1)  #当只有一个元素时
>>>temp
>>>1
>>>type(temp)
>>><class 'int'>#temp为int类型,所以此时只关注()是不能完全定义为元祖的
>>>temp(1,)
>>>type(temp)
>>><class 'tuple'>  #在元素后面加‘,‘后,则成为元祖,不能单纯靠’()'
>>>temp[::]
>>>(1,)
>>>#看下面的例子,加深印象
>>> 2 * (2)
4
>>> 2 * (2,)
(2, 2)
>>> 
2.更新和删除元祖
>>> temp = (1, 2, 3, 4)
>>> temp[1] = 3 #修改第二个元素
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    temp[1] = 3
TypeError: 'tuple' object does not support item assignment
>>> temp = (1, 2, 3, 4)#在元素2后面加入1234
>>>temp 1 = (1234,)
>>> temp = temp[:2] + temp1 + temp[2:]
>>> temp
(1, 2, 1234, 3, 4)
>>> 
3.元祖相关操作
删除一个元祖
>>> del temp #当元祖没有被其他变量引用时,系统会自动回收
>>> temp
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    temp
NameError: name 'temp' is not defined
>>> 
支持关系操作、逻辑操作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Python中,元组(tuple)是不可变的序列类型,即它的元素不可修改。所以元组对象本身并没有提供replace()方法用于替换元素。如果你想要替换元组中的某个元素,你可以将元组转换为列表,然后使用列表的replace()方法进行替换,最后再将列表转换回元组。下面是一个示例代码: ``` # 将元组转换为列表 my_tuple = (1, 2, 3, 4, 5) my_list = list(my_tuple) # 使用列表的replace()方法替换元素 my_list = 10 # 将列表转换回元组 new_tuple = tuple(my_list) print(new_tuple) ``` 这段代码将元组 `(1, 2, 3, 4, 5)` 转换为列表 `my_list`,然后使用列表的replace()方法将第三个元素替换为10。最后将列表转换回元组并打印出来,结果为 `(1, 2, 10, 4, 5)`。希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [python 列表 元祖 集合](https://blog.csdn.net/weixin_39652646/article/details/110995188)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [基于python元祖与字典与集合的粗浅认识](https://download.csdn.net/download/weixin_38689338/12872428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值