python中, 有6种数据类型, 那它们之间能不能互相转换? 怎样转换? 这篇就来说说, 数据类型之间的转换
数据类型之间的转换, 主要有以下函数
1 int()
将其它类型转为整型
int(x=0) -> integer
int(x, base=10) -> integer浮点型:
会去掉小数部分
In [1]: int(1.0)
Out[1]: 1纯数字字符串
In [2]: int("1")
Out[2]: 1布尔型
In [4]: int(True)
Out[4]: 1
In [5]: int(False)
Out[5]: 02 float()
将其它类型转为浮点型
float(x) -> floating point number整型
会在结尾加上 .0
In [9]: float(1)
Out[9]: 1.0纯浮点型字符串
In [10]: float("1.1")
Out[10]: 1.1布尔型
In [11]: float(True)
Out[11]: 1.0
In [12]: float(False)
Out[12]: 0.03 complex()
将其它类型转为复数
complex(real[, imag]) -> complex number整型, 浮点型 和 纯数字字符串, 纯浮点数字符串, 布尔值True
都会在结尾加上 +0j
In [17]: complex(1)
Out[17]: (1+0j)
In [18]: complex(1.0)
Out[18]: (1+0j)
In [19]: complex("1.0")
Out[19]: (1+0j)
In [20]: complex("1")
Out[20]: (1+0j)
In [21]: complex(True)
Out[21]: (1+0j)布尔值 Flase
In [22]: complex(False)
Out[22]: 0j4 str()
将其它类型转为字符串
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str所有类型都可以转为str, 类型会转为str, 展示方式会在两边加上引号
In [27]: str(1)
Out[27]: '1'
In [28]: str(1.0)
Out[28]: '1.0'
In [29]: str(0j)
Out[29]: '0j'
In [30]: str(True)
Out[30]: 'True'5 bool()
将其它类型转为布尔类型
bool(x) -> bool以下值会转为布尔值: False
"", 0, 0.0, [], (), {}, set(), 0j, False
In [34]: for i in ["", 0, 0.0, [], (), {}, set(), 0j, False]:
...: print(i, "is", bool(i))
...:
is False
0 is False
0.0 is False
[] is False
() is False
{} is False
set() is False
0j is False
False is False6 list()
接下来就是可迭代序列的转换
字符串, 列表, 元组, 字典, 集合
将其它可迭代序列转为列表
list() -> new empty list
list(iterable) -> new list initialized from iterable's items字符串
每个字符都会成为列表的一个元素
In [36]: list("abc")
Out[36]: ['a', 'b', 'c']集合, 元组
In [37]: list({"a", "b", "c"})
Out[37]: ['c', 'a', 'b']
In [38]: list(("a", "b", "c"))
Out[38]: ['a', 'b', 'c']字典
提取键为新的列表
In [39]: list({"a": 1, "b":2, "c": 3})
Out[39]: ['a', 'b', 'c']7 dict()
将其它可迭代序列转为字典类型
dict(mapping) -> new dictionary initialized from a mapping object's
dict(iterable) -> new dictionary initialized as if via
dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list.转字典需要注意一下, 只能是长度都为2的嵌套列表或元组
如下
In [50]: dict([["a", 1], ["b",2]])
Out[50]: {'a': 1, 'b': 2}
In [51]: dict((["a", 1], ["b",2]))
Out[51]: {'a': 1, 'b': 2}
In [52]: dict((("a", 1), ("b",2)))
Out[52]: {'a': 1, 'b': 2}还有个特殊的, 像这样, 当然这也不是今天要说的内容
In [67]: dict(a="1",b="2")
Out[67]: {'a': '1', 'b': '2'}8 tuple()
将其它可迭代序列转为元组
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items列表和集合
In [54]: tuple([1,2,3])
Out[54]: (1, 2, 3)
In [55]: tuple({1,2,3})
Out[55]: (1, 2, 3)
In [56]: tuple("abc")
Out[56]: ('a', 'b', 'c')字典类型
提取键为新元组
In [57]: tuple({"a":1,"b":2})
Out[57]: ('a', 'b')9 set()
将其它可迭代序列转为集合类型
set(iterable) -> new set object列表和元组
In [59]: set([1,2,3])
Out[59]: {1, 2, 3}
In [60]: set((1,2,3))
Out[60]: {1, 2, 3}
In [61]: set("abc")
Out[61]: {'a', 'b', 'c'}字典
提取键为新的集合对象
In [62]: set({"a":1, "b":2})
Out[63]: {'a', 'b'}以上转换数据类型主要使用的函数, 有错误或者不懂的可以直接回复哦!