網站首頁 編程語言 正文
Python 代碼庫之Tuple如何append元素
tuple不像array給我們提供了append函數,我們可以通過下面的方式添加
t=[1,3,4,5]
k=()
for item in t:
k=k+(item,)
Python tuple與list、append與extend
tuple 里邊的 list 可修改:
>> t = (1, 2, [3, 4])
>>t[2].append(5)
>> t?
(1, 2, [3, 4, 5])
tuple的切片還是tuple,list的切片還是list(這可能是一句廢話)
>>>type(t[0:2])
<class 'tuple'>
>>>type(l[0:3])
<class 'list'>
1. tuple可讀不可寫
tuple的元素不可作左值,list反之
>>>t = (1, 2, 3)
>>>t[:]
(1, 2, 3)
>>>t[0] = 4
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>l = [1, 2, 3]
>>>l[:]
[1, 2, 3]
>
>>>l[0] = 4
>
2. 兩者的成員函數
tuple幾乎沒什么成員函數,list卻有著豐富的成員函數:
>>>t = (1, 2, 3, 3, 4)
>>>dir(t)
# 有意義的成員函數只有`count`、`index`
# count,記錄元組中某一元素出現的次數,index返回值所在的下標
>>>t.count(3)
2
>>>t.count(2)
1
>>>t.index(4)
4
>>>l=[1, 2, 3, 4]
dir(l)
3. 彼此間類型轉換
>>>l = [1, 2, 3, 3, 4]
>>>tuple(l)
(1, 2, 3, 3, 4)
>>>t = (1, 2, 3, 3, 4)
>>>list(t)
[1, 2, 3, 3, 4]
>>>(l)
[1, 2, 3, 3, 4]
>>>[t] ? ? ? ? ? ? ? ? # 由元組組成的list
[(1, 2, 3, 3, 4)]
總結
原文鏈接:https://blog.csdn.net/iCloudEnd/article/details/99498456
相關推薦
- 2022-09-01 MongoDB實現查詢、分頁和排序操作以及游標的使用_MongoDB
- 2022-07-24 C語言與C++中關于字符串使用的比較_C 語言
- 2022-04-03 C++中的運算符重載詳解_C 語言
- 2022-04-09 數據庫連接池Driud使用JbbcUtils工具包
- 2022-03-01 格式化日期‘年月日-時分秒’方法
- 2023-02-05 expect實現Linux自動登陸遠程機器腳本實例_Linux
- 2022-12-03 C++實現重載矩陣的部分運算符_C 語言
- 2022-04-18 python中start和run方法的區別_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支