網站首頁 編程語言 正文
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-01-16 npm run dev 報錯:missing script:dev
- 2022-06-07 C語言非遞歸算法解決快速排序與歸并排序產生的棧溢出_C 語言
- 2022-04-02 jquery實現邊框特效_jquery
- 2022-09-15 C++中的整形字節數_C 語言
- 2022-06-01 C語言?詳細分析結構體的內存對齊_C 語言
- 2023-04-02 Golang?WaitGroup實現原理解析_Golang
- 2022-04-10 小程序播放文件流音頻
- 2022-07-24 Nginx?配置?HTTPS的詳細過程_nginx
- 最近更新
-
- 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同步修改后的遠程分支