列表转字符串,列表转元组,元组转列表

''' 将列表转换成字符串 '''

list1 = [str(x) for x in range(10)]
print(type(list1[0]))
str1 = ''.join(list1)
print(str1)

list1 = ['abe', 1, 3, 4, 'c']
list_str = [str(x) for x in list1]
str2 = ''.join(list_str)
print(str2)
'''
列表转元组
'''

# 可以直接使用tuple()函数

list = [34, 56, 12, 56, 8, 12, 90, 6, 2, 31]
print(list, type(list))
tp = tuple(list)
print(tp, type(tp))


'''
运行结果:
[34, 56, 12, 56, 8, 12, 90, 6, 2, 31] <class 'list'>
(34, 56, 12, 56, 8, 12, 90, 6, 2, 31) <class 'tuple'>
'''
'''
 元组转列表

# 可以直接使用list()函数

注意点: 在给变量命名的时候不要使用list、tuple等,这些都是函数名
要自己定义变量名,不然会报错以下错误:
TypeError: 'list' object is not callable
'''

list1=[1,2,3]
tup1=tuple(list1)
print(tup1)
print(list(tup1))


# 运行结果
'''
(1, 2, 3)
[1, 2, 3]
'''

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章