Python入门实践14 ——数据类型转换
数据类型转换
一、目标
掌握简单类型和结构类型的数据间转换的函数功能。
二、要点
1、简单数据类型转换
1)、其他数据类型转换为int
函数格式:int(x [,base])
例:int("18")
2)、其他数据类型转换为float
函数格式:float(x)
例:float(1)或者float("1")
3)、其他数据类型转换为string
函数格式:str(x)
例:str(1)
2、list、tuple、dict、set间的转换
1)、list 转换为set
l1 = [1, 2, 4, 5]
s1 = set(l1)
print(type(s1))
2)、set转换为list
s1 = set([1, 2, 3, 4])
l1 = list(s1)
print(type(l1))
3)、tuple 转换为set
t1 = (1, 2, 3, 4)
s1 = set(t1)
print(type(s1))
4)、set转换为tuple
s1 = set([1, 2, 3, 4])
t1 = tuple(s1)
print(type(t1))
5)、list转tuple
l1 = [1, 2, 4, 5]
t1 = tuple(l1)
print(type(t1))
6)、tuple转list
t1 = (1, 2, 3, 4)
l1 = list(t1)
print(type(l1))
7)、list转dict
list1=[('a',1),('b',2),('c',3)]
dict1={k:v for k,v in list1}
dict2={v:k for k,v in list1}
print(dict1)
print(dict2)
3、python常用类型转换函数
函数格式
使用示例
描述
int(x [,base])
int("8")
可以转换的包括String类型和其他数字类型,但是会丢失精度
float(x)
float(1)或者float("1")
可以转换String和其他数字类型,不足的位数用0补齐,例如1会变成1.0
complex(real ,imag)
complex("1")或者complex(1,2)
第一个参数可以是String或者数字,第二个参数只能为数字类型,第二个参数没有时默认为0
str(x)
str(1)
将数字转化为String
repr(x)
repr(Object)
返回一个对象的String格式
eval(str)
eval("12+23")
执行一个字符串表达式,返回计算的结果,如例子中返回35
tuple(seq)
tuple((1,2,3,4))
参数可以是元组、列表或者字典,wie字典时,返回字典的key组成的集合
list(s)
list((1,2,3,4))
将序列转变成一个列表,参数可为元组、字典、列表,为字典时,返回字典的key组成的集合
set(s)
set(['b', 'r', 'u', 'o', 'n'])或者set("asdfg")
将一个可以迭代对象转变为可变集合,并且去重复,返回结果可以用来计算差集x - y、并集x | y、交集x & y
frozenset(s)
frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
将一个可迭代对象转变成不可变集合,参数为元组、字典、列表等,
chr(x)
chr(0x30)
chr()用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。返回值是当前整数对应的ascii字符。
ord(x)
ord('a')
返回对应的 ASCII 数值,或者 Unicode 数值
hex(x)
hex(12)
把一个整数转换为十六进制字符串
oct(x)
oct(12)
把一个整数转换为八进制字符串
数据类型转换——思维导图
三、步骤
1、新建新建ex13.py文件。
2、录入实例中代码。
3、运行。
四、实例(Python 3.0+)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'jungle'
__mtime__ = '2019-08-30'
"""
#1、简单数据类型转换
#1)、其他数据类型转换为int
print(int("18"));
#2)、其他数据类型转换为float
print(float(1));
#3)、其他数据类型转换为string
print(str(1234));
#2、list、tuple、dict、set间的转换
#1)、list 转换为set
l1 = [1, 2, 4, 5];
s1 = set(l1);
print(type(s1));
print(s1);
#2)、set转换为list
s1 = set([1, 2, 3, 4]);
l1 = list(s1);
print(type(l1));
print(l1);
#3)、tuple 转换为set
t1 = (1, 2, 3, 4);
s1 = set(t1);
print(type(s1));
print(s1);
#4)、set转换为tuple
s1 = set([1, 2, 3, 4]);
t1 = tuple(s1);
print(type(t1));
print(t1);
#5)、list转tuple
l1 = [1, 2, 4, 5]
t1 = tuple(l1)
print(type(t1))
print(t1);
#6)、tuple转list
t1 = (1, 2, 3, 4);
l1 = list(t1);
print(type(l1));
print(l1);
#7)、list转dict
list1=[('a',1),('b',2),('c',3)];
dict1={k:v for k,v in list1};
dict2={v:k for k,v in list1};
print(dict1);
print(dict2);
五、运行输出:
18
1.0
1234
{1, 2, 4, 5}
[1, 2, 3, 4]
{1, 2, 3, 4}
(1, 2, 3, 4)
(1, 2, 4, 5)
[1, 2, 3, 4]
{'a': 1, 'b': 2, 'c': 3}
{1: 'a', 2: 'b', 3: 'c'}
注:
1、撰写内容来源于个人收集的文献,属学术探究范畴。
2、版权属于时进军个人,转载需注明。