数据类型
python拥有如下数据类型:
类型 | 描述 |
int | 整型,如 1,2,3 |
float | 浮点,如1.2, 2.3 |
complex | 复数 |
bool | 布尔:True 和 False |
str | 字符串,如 ‘hello’ |
list | 列表, [1,2,3], [“a”,“b”,“c”] |
tuple | 元祖,只读的数组,(“a”,“b”,“c”) |
dict | 字典, key -value键值对形式,{} |
整型int
# a和b都为整型
a, b= 3, 2
print(type(a))
print(type(a/b))
浮点型float
a, b= 3.1, 2.13
print(type(a))
print(type(b))
布尔型bool
if True:
print(“True”)
if False:
print(“False”)
字符串str
python中可以使用单引号(’)、双引号(")、三引号(’’'或""")表示。 去除空格:lstrip()、rstrip()、strip()=>去首部、尾部、首尾部
a = "hello"
print(type(a))
列表 list
- 基本使用
list = [111, 222, 333, 444, 555]
print(list)
# 获取列表长度 使用len()获取列表长度
print(len(list))
# 获取某个元素 使用下标来获取元素list[0],第一个元素的下标为0,使用-1可以获得最后一个元素
print(list[0])
print(list[-1])
# 第一个位置开始每隔2个取值
print(list[1::2])
- 数组新增元素
# 方式一:使用append()添加元素到数组最后
list = ["hello", "world"]
list.append("!")
print(len(list))
print(list)
# 方式二:insert(n,object)添加元素到指定位置
list = ["hello", "world"]
list.insert(0, "!")
print(list) # output:['!', 'hello', 'world']
- 删除元素
# 方式一:使用del(index)关键字
list = ["hello", "world", "!"]
del list[0]
print(list) # output:['world', '!']
# 方式二:使用pop()删除元素最后一项
list = ["hello", "world", "!"]
list.pop()
print(list) # output:['hello', 'world']
# 方式三:如果你知道要删除的值,可以使用remove删除
list = ["hello", "world", "!"]
list.remove("hello")
print(list) # output:['world', '!']
- 查询
# in查询 查询元素是否存在数组使用in查询
list = ["hello", "world", "!"]
dstr = "hello2"
if dstr in list:
print("存在")
else:
print("不存在")
- 最大值、最小值、求和
list = [10, 4, 6, 8]
print(min(list)) # output:4
print(max(list)) # output:10
print(sum(list)) # output:28
- 排序
# 使用sort()对列表永久性排序
list = ["ahref", "focus", "mouse", "click"]
list.sort()
print(list)
# 如果你需要一个**相反的排序,使用sort(reverse=True)**即可
list.sort(reverse=True)
print(list)
# 使用sorted(),对列表临时排序
list = ["ahref", "focus", "mouse", "click"]
print(sorted(list)) # output:['ahref', 'click', 'focus', 'mouse']
print(list) # output:['ahref', 'focus', 'mouse', 'click']
元组 tuple
# python中有括号()表示元祖,是一种只读的列表类型,元素值不能被修改
list = ("ahref", "focus", "mouse", "click")
print(list[1])
# list[1] = "myfocuse" # output:报错,元祖的元素不能被修改
# 注意:元祖的元素虽然不能修改,但元祖的接受变量是运行修改的
list = ("ahref", "focus", "mouse", "click")
print(list) # output:('ahref', 'focus', 'mouse', 'click')
list = ("dbclick", "keyup")
print(list) # output:('dbclick', 'keyup')
字典 dict
# python中用{}表示字典,字典是用键值对表示的,和列表相比,字典是无须的对象集合
dict = {}
dict["name"] = "laowang"
dict["age"] = 18
print(dict)
print(dict["name"])
print(dict.keys())
print(dict.values())
for key, value in dict.items():
print("key:"+key)
print("value:"+value)
类型转换方法集合
chr(i) 把一个ASCII数值,变成字符
ord(i) 把一个字符或者unicode字符,变成ASCII数值
oct(x) 把整数x变成八进制表示的字符串
hex(x) 把整数x变成十六进制表示的字符串
str(obj) 得到obj的字符串描述
list(seq) 转换成列表
tuple(seq) 转换成元祖
dict() 转换成字典
int(x) 转换成一个整数
float(x) 转换成一个浮点数
complex(x) 转换成复数