python全栈开发《67.不同数据类型间的转换:列表集合元组的转换》
列表、元组和集合间转换的函数
例1:
# coding:utf-8
a = [1,2,3]
b = (1,2,3)
c = {1,2,3}
print(tuple(a),set(a))
print(type(tuple(a)),type(set(a)))
print(tuple(a) is b)
print(set(a) is c)
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/change/bin/python /Users/llq/PycharmProjects/pythonlearn/change/change_list_tuple_set.py
(1, 2, 3) {1, 2, 3}
<class 'tuple'> <class 'set'>
False
False
进程已结束,退出代码为 0
运行结果显示False,是因为a和b不是相同的内存地址。
例2:
# coding:utf-8
a = [1,2,3]
b = (1,2,3)
c = {1,2,3}
print(tuple(a),set(a))
print(type(tuple(a)),type(set(a)))
print(tuple(a) is b)
print(set(a) is c)
print(list(b),set(b))
print(list(c),tuple(c))
print(list(a))#运行结果:[1,2,3],没有任何的变化。
print(str(a),type(str(a)))#运行结果:'[1,2,3]'
print(str(b),type(str(b)))
print(str(c),type(str(c)))
print(list(str(a)))
print(tuple(str(b)))
print(set(str(c)))
_a = str(a)
_b = list(_a)
print(_b)
运行结果:
/Users/llq/PycharmProjects/pythonlearn/pythonlearn/change/bin/python /Users/llq/PycharmProjects/pythonlearn/change/change_list_tuple_set.py
(1, 2, 3) {1, 2, 3}
<class 'tuple'> <class 'set'>
False
False
[1, 2, 3] {1, 2, 3}
[1, 2, 3] (1, 2, 3)
[1, 2, 3]
[1, 2, 3] <class 'str'>
(1, 2, 3) <class 'str'>
{1, 2, 3} <class 'str'>
['[', '1', ',', ' ', '2', ',', ' ', '3', ']']
('(', '1', ',', ' ', '2', ',', ' ', '3', ')')
{' ', '{', '1', '}', '2', '3', ','}
['[', '1', ',', ' ', '2', ',', ' ', '3', ']']
进程已结束,退出代码为 0
str可以转所有的类型。通过str直接将这三种类型进行转换之后,是一个不可逆的转换。print(list(str(a)))
执行的时候,优先执行str函数,再执行list函数。相当于:
_a = str(a)
_b = list(_a)
print(_b)
总结:如果函数内部又包裹了函数,优先执行内部的函数。一层一层往外去执行。