Python中列表与元组的乘法操作示例

yipeiwu_com7年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python中range()与xrange()用法分析

python中range()与xrange()用法分析

本文实例讲述了python中range()与xrange()用法。分享给大家供大家参考,具体如下: 据说range比xrange开销要大,原因是range会直接生成一个list对象,而x...

Python 互换字典的键值对实例

1.zip dic = {'a':1, 'b':2, 'c':3} dic_new = dict(zip(dic.values(), dic.keys())) print(dic_n...

python实现类之间的方法互相调用

all.py from son import * class ALL(): def __init__(self): self.mSon = SON(self) def get...

Python使用combinations实现排列组合的方法

好久没有写博客了!昨天小牛在上海举办了牛友见面会,现场优惠还是比较大,心仪已久加上一时脑热就入手了。以为会有多么开心,其实目前最大的感受就是焦虑!担心电动车被偷,担心电池被偷,担心路上突...

CentOS安装pillow报错的解决方法

安装pillow出现以下问题: ValueError: jpeg is required unless explicitly disabled using --disable-jpe...