如何实现tuple与list 的转换
1、tp = (11, 22, 33, 44)
print(type(tp))
tp_list = list(tp)
print(type(tp_list))
这里有个tuple,转换为list,我们用list()函数就可以转换了。
2、tp = (11, 22, 33, 44)
tp_list = []
for i in tp:
tp_list.append(i)
print(tp_list)
我们也可以创建一个空的列表,然后用for循环往列表里面添加数据从而生成list。
3、tp = (11, 22, 33, 44)
tp_list = list()
for i in tp:
tp_list.append(i)
print(tp_list)
创建列表的形式也可以允许这样书写,结果是一样的。
4、l = [11, 22, 33, 44]
print(tuple(l))
那么实际上列表转换为元组也是可以用这个类似方法的,因为这里有tuple()函数。
5、但是我们不能用循环添加的方法来转换为tuple,因为tuple是不可改变的数据类型。
6、l = [11, 22, 33, 44]
print(tuple(l[:]))
我们还可以用切片的方法来进行转换,可以灵活运用。
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:135
阅读量:172
阅读量:69
阅读量:161
阅读量:185