python-7-数据结构与类型转换

谁说我不能喝 提交于 2019-12-06 04:30:12

前言

python除了前面所说的基础类型,我们这里也需要讲解下数据结构,数据结构里面存放的是基础类型,如数字等同时也可以嵌套。

  • 不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
  • 可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。

一、数据结构

1、list 列表,符号:[xxx]

# list 列表
list1 = [1, 'XL', [1, 2]]
print('列表:', type(list1))

 2、tuple 元组,只读,不可写入与修改

# tuple 元组,只读不可写入与修改
tuple1 = (1, 2, 'XL', {"sad": 2})
print('元组:', type(tuple1))

 3、dict 字典,键值对

# dict 字典,键值对
dict1 = {"name": "XL", "age": [{"name": 123}]}
print('字典:', type(dict1))

 4、set 集合

# set 集合
set1 = {'XL', '小龙', 123}
print('集合:', type(set1))

二、类型转换

类型转换我们会有许多场景用到的,比如 input 的时候输入的都是字符串,我们要转换其它类型。

1、int --> str

# 1、int --> str
i = 1
s = str(i)
print(type(s))

 2、str --> int,纯数字才可以转换

# 2、str --> int,纯数字才可以转换
q = '1'
w = int(q)
print(type(w))

 3、int --> bool, 非0就是 True

# 3、int --> bool, 非0就是 True
e = -1
b = bool(e)
print(type(b))
print(b)

 4、bool --> int

# 4、bool --> int
# True --> 1
# False --> 0

5、str --> bool,非空字符串都是 True

# 5、str --> bool,非空字符串都是 True
# s = '' --> False
# s = 'xx' --> True

QQ交流群:99941785

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!