python数据类型
-
数据类型
Python有五个标准的数据类型:
-
Numbers(数字)
int
long
float
complex(复数)
-
String(字符串)
-
List(列表)
-
Tuple(元组)
-
Dictionary(字典)
其中属于集合类型的数据类型有 列表、元组及字典
-
-
元祖与列表的区别
列表是动态数组,它们是可变且可以重设长度(改变其内部元素的个数)
元祖是静态数组,它们不可变,且其内部数据一旦创建便无法修改
元祖缓存于python运行环境,这意味着我们每次使用元祖时无须访问内核去分配内存
-
字典、字符串、列表之间转换
-
列表转为字符串
l = ["hi","hello","world"] print(" ".join(l)) #若想转为列表中元素以空格隔开的字符串 #hi hello world print("".join(l))#若不想转为空格隔开 #hihelloworld
-
字符串转为列表
str1 = "hi hello world" print(str1.split(" ")) #输出: ['hi', 'hello', 'world'] a='abc' list(a) #输出 ['a','b','c']
-
字符串转字典
import json >>> user_info= '{"name" : "john", "gender" : "male", "age": 28}' >>> user_dict = json.loads(user_info) >>> user_dict {u'gender': u'male', u'age': 28, u'name': u'john'}
-
字典转字符串
import json user_dict={u'gender': u'male', u'age': 28, u'name': u'john'} user_info=json.dumps(user_dict) #输出 '{"name" : "john", "gender" : "male", "age": 28}'
-
列表转字典
##将两个列表转为字典 l1=["hi","hello","world"] l2=[1,2,3] dict(zip(l1,l2)) #输出 {'hi': 1, 'hello': 2, 'world': 3} ##嵌套列表转为字典 l=[['a',1],['b',2],['c',3]] dict(l) #输出 {'a': 1, 'b': 2, 'c': 3}
-
字典转为列表
d={'a': 1, 'b': 2, 'c': 3} list(d.keys()) #输出 ['a','b','c'] list(d.values) #输出 [1,2,3]