本文實例講述了Python中列表與元組的乘法操作。分享給大家供大家參考,具體如下:
直接上code吧,還可以這么玩兒
列表乘法:
li=[1,] li=li*3 print(li)
out:
[1, 1, 1]
元組乘法:
>>> t=(1,2) >>> t*3 (1, 2, 1, 2, 1, 2)
但字典,集合不能這么玩
例如:
>>> dict1={'k1':1,'k2':2} >>> dict1*2 #報錯 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> dict1*2 TypeError: unsupported operand type(s) for *: 'dict' and 'int' >>>
另外,字符串也可以使用乘法,例如:
>>> str1='hello python!' >>> str1*3 'hello python!hello python!hello python!' >>>
注意:在元組的定義中:(1,)
代表著元組,(1,)*3
可得到(1, 1, 1)
而(1)則只會被視為一個整數,
(1)*3
會得到3
更多Python相關內容感興趣的讀者可查看本站專題:《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。