list(列表):list是一种有序的集合,可以随时添加和删除其中的元素。
tuple(元祖):tuple和list非常类似,但是tuple一旦初始化就不能修改,比如同样是列出同学的名字:
python3下运行
python2下运行
python2下运行
python3下运行
list和tuple是Python内置的有序集合,一个可变,一个不可变。
list转为tuple:
temp_list = [1,2,3,4,5]
将temp_list进行强制转换:tuple(temp_list)
查看是否转换成功:print type(temp_list)
tuple 转为list:
temp_tuple = (1,2,3)
方法类似,也是进行强制转换即可:list(temp_tuple)
查看是否转换成功:print type(temp_tuple)
拓展说明:
str转list
list = list(str)
2. list转str
str= ''.join(list)
3. tuple list相互转换
tuple=tuple(list)
list=list(tuple)
Python中,tuple和list均为内置类型,
以list作为参数将tuple类初始化,将返回tuple类型
tuple([1,2,3]) #list转换为tuple以tuple作为参数将list类初始化,将返回list类型
list((1,2,3)) #tuple转换为listTuple是元组的意思,元组是不能修改的;list是列表的意思,列表是可以修改的;在Python中实现Tuple和list的转换可以通过两个函数list()、Tuple()实现转换。举例如下:
将元组a转换为列表b,b=list(a)
将列表b转换为元组a,a=Tuple(b)