本文實例講述了Python中列表與元組的乘法操作。分享給大家供大家參考,具體如下:
直接上code吧,還可以這么玩兒
列表乘法:
li=[1,]li=li*3print(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*2TypeError: 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)則只會被視為一個整數(shù),(1)*3會得到3
更多Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python列表(list)操作技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選