# str to int
int("1") # 1
int("1.1") # 错误
# float to int
int(1) # 1
int(1.1) # 1, 精度损失
# str to float
float("1.1") # 1.1
# int to float
float(1) # 1.0 自动补零
str
)# others to str
str()
bool
)True
# 0、空字符串、空列表、空元组、空字典、空集合
False
# 其他
list
)、元组(tuple
)、字典(dict
)、集合(set
)# 可迭代的对象 to list
list()
# 可迭代的对象 to tuple
tuple()
# 键值对
dict()
# 可迭代的对象 to set
set()
# 十进制 to 二进制
bin(31) # 0b11111
# 十进制 to 八进制
oct(31) # 0o37
# 十进制 to 十六进制
hex(31) # 0x1f
# 二进制(八进制)(十六进制) to 十进制
int(进制数据, 具体进制)
int(hex(31), 16)
abs
a = -1
print(abs(-1)) # 1
divmod
dividend = 9
divisor = 2
res = divmod(dividend, divisor)
print(res, type(res)) # (4, 1) <class 'tuple'>
discuss, remainder = res
print(discuss, remainder) # 4 1
round
round(number[, ndigits])
# 默认ndigits = 0, 表示取整
a = 3.5
b = 4.5
print(round(a, 0)) # 4.0
print(round(b, 0)) # 4.0
round()
不一定能避免二进制浮点数表示的精度问题。a = 3.35
b = 4.45
c = 5.55
print(round(a, 1)) # 3.4
print(round(b, 1)) # 4.5
print(round(c, 1)) # 5.5
pow
# 两个参数,幂次
# 3的2次方
pow(3, 2) # 9
# 三个参数,幂次取余数
# 3的2次方,再对2进行取余数
pow(3, 2, 2) # 1
sum
、最小值min
、最大值max
# 可迭代是整型或者浮点型
print(sum([1, 3.0, 5])) # 9.0
print(min([1, 3.0, 5])) # 1
print(max([1, 3.0, 5])) # 5
complex
# complex(re, im) : 具有实部 re、虚部 im 的复数。im 默认为零。
print(complex(3)) # (3+0j)
print(complex(3, 5)) # (3+5j)
reversed
# 字符串
a = "Bruce"
b = reversed(a)
print(b, type(b)) # <reversed object at 0x000001E3AE20AE00> <class 'reversed'>
print(list(b)) # ['e', 'c', 'u', 'r', 'B']
# 列表
a = [1, 2, 3, 4, 5]
b = reversed(a)
print(b, type(b)) # <list_reverseiterator object at 0x0000016AEB740D90> <class 'list_reverseiterator'>
print(list(b)) # [5, 4, 3, 2, 1]
slice
、计算长度len
a = [1, 2, 3, 4, 5]
print(a[::-1]) # [5, 4, 3, 2, 1]
s = slice(0, 5, 2)
print(a[s]) # [1, 3, 5]
a = [1, 2, 3, 4, 5]
b = (1,)
c = {"a": 12}
print(len(a), len(b), len(c))
sorted
sorted(Iterable, key=函数(排序规则), reverse=False)
Iterable
: 可迭代对象key
: 排序规则(排序函数), 在sorted
内部会将可迭代对象中的每一个元素传递给这个函数的参数. 根据函数运算的结果进行排序reverse
:True: 倒叙, False: 正序# 简单列表
a = [1, 6, 3, 9, 5]
print(sorted(a))
# [1, 3, 5, 6, 9]
# 使用lambda函数列表, 根据列表内容长度排序
a = ["111111", "11", "1", "1111", "111"]
print(sorted(a, key=lambda x: len(x)))
# ['1', '11', '111', '1111', '111111']
# 字典排序
a = {2: "a", 1: "c", 3: "b"}
print(sorted(a))
print(sorted(a.values()))
print(sorted(a.items()))
print(sorted((a.items()), key=lambda x: x[1]))
# [1, 2, 3]
# ['a', 'b', 'c']
# [(1, 'c'), (2, 'a'), (3, 'b')]
# [(2, 'a'), (3, 'b'), (1, 'c')]
enumerate
(常用)# 默认
a = [1, 6, 3]
for index, data in enumerate(a):
print(f"index:{index},data:{data}")
# index:0,data:1
# index:1,data:6
# index:2,data:3
# 指定开始数字
a = ["apple-10", "banana-12", "peach-20"]
for index, data in enumerate(a, start=1):
name, price = data.split("-")
print(f"商品编号{index},商品名称:{name},商品价格{price}")
# 商品编号1,商品名称:apple,商品价格10
# 商品编号2,商品名称:banana,商品价格12
# 商品编号3,商品名称:peach,商品价格20
format
# 对齐方式
s = "hello world!"
print(format(s, "^20")) # 居中
# hello world!
print(format(s, "<20")) # 左对齐
# hello world!
print(format(s, ">20")) # 右对齐
# hello world!
# 进制转换
print(format(97, 'b')) # 二进制:1100001
print(format(97, 'c')) # 转换成unicode字符:a
print(format(97, 'd')) # ?进制:97
print(format(97, 'n')) # 和d?样:11
print(format(97)) # 和d?样:11
print(format(97, 'o')) # 八进制:141
print(format(10, 'x')) # 十六进制(?写字母):a
print(format(10, 'X')) # 十六进制(大写字母):A
# 科学计数法
print(format(123456789, 'e')) # 科学计数法. 默认保留6位小数,自动补零:1.234568e+08
print(format(123456789, '0.2e')) # 科学计数法. 保留2位小数(小写):1.23e+08
print(format(123456789, '0.2E')) # 科学计数法. 保留2位小数(大写):1.23E+08
print(format(1.23456789, 'f')) # 小数点计数法. 保留6位小数:1.234568
print(format(1.23456789, '0.2f')) # 小数点计数法. 保留2位小数:1.23
print(format(1.23456789, '0.10f')) # 小数点计数法. 保留10位小数:1.2345678900
print(format(1.23456789e+3, 'F')) # 小数点计数法. 很大的时候输出INF:1234.567890
bytes
、获取字节数组bytearray
、获取对象的字符串格式repr
# bytes() 把字符串转化成bytes类型
print(bytes("hello, 小明", encoding="utf8"))
# b'hello, \xe5\xb0\x8f\xe6\x98\x8e'
# bytearray返回一个新字节数组. 这个数字的元素是可变的, 并且每个元素的值得范围是[0,256),一个字节的大小
a = "小明"
bytearray_ = bytearray(a, encoding="utf8")
print(bytearray_, type(bytearray_))
# bytearray(b'\xe5\xb0\x8f\xe6\x98\x8e') <class 'bytearray'>
print(bytearray_[0])
# 229
# repr() 返回一个对象的string形式
text = "my\nname\nis\bruce"
print(text)
print(repr(text))
# my
# name
# iruce
# 'my\nname\nis\x08ruce'
# ord根据字符寻找unicode编码对应的位置
unicode_code = ord('🐅')
print(unicode_code)
# 128005
# chr更具unicode编码对应位置找字符
character = chr(128005)
print(character)
# 🐅
# ascii转义成ascii字符,没有就是unicode码的位置,十六进制表示
print(ascii("a"))
print(ascii("你"))
# 'a'
# '\u4f60'
frozenset
# 这是不可变集合
# 所以也是不支持切片,可去重
# 但是不支持添加和删除
a = frozenset([1, 2, 2])
print(a, type(a))
for i in a:
print(i)
# frozenset({1, 2}) <class 'frozenset'>
# 1
# 2
all
and
同理name = "bruce"
age = "18"
flag = name == "bruce" and age == "18"
print(flag)
flag = all([name == "bruce", age == "18"])
print(flag)
# True
# True
any
or
同理name = "bruce"
age = "18"
flag = name == "bruce" and age == "18"
print(flag)
flag = all([name == "bruce", age == "20"])
print(flag)
# True
# False
zip
(拉链函数)name = ["bruce", "tom", "lucy"]
age = ["15", "18", "27"]
zip_ = zip(name, age)
print(zip, type(zip))
# <class 'zip'> <class 'type'>
for i in zip_:
print(i)
# <class 'zip'> <class 'type'>
# ('bruce', '15')
# ('tom', '18')
# ('lucy', '27')
name = ["bruce", "tom", ]
age = ["15", "18", "27"]
zip_ = zip(name, age)
for i in zip_:
print(i)
# ('bruce', '15')
# ('tom', '18')
name = ["bruce", "tom", "lucy"]
age = ["15", "18", "27"]
zip_ = zip(name, age)
dict_ = dict(zip_)
print(dict_)
# {'bruce': '15', 'tom': '18', 'lucy': '27'}
filter
fiter(function, Iterable)
function
: 用来筛选的函数,返回判断结果
?lter
中会自动的把iterable
中的元素传递给function
function
返回的True
或者False
来判断是否保留留此项数据Iterable
: 可迭代对象def func(i):
# 保留奇数
return i % 2
num_list = [i for i in range(1, 10)]
filter_ = filter(func, num_list)
print(filter_, type(filter_))
print(list(filter_))
# <filter object at 0x000001F67E77B640> <class 'filter'>
# [1, 3, 5, 7, 9]
num_list = [i for i in range(1, 10)]
filter_ = filter(lambda x: x % 2, num_list)
print(filter_, type(filter_))
print(list(filter_))
# <filter object at 0x000001F67E77B640> <class 'filter'>
# [1, 3, 5, 7, 9]
map
map(function, iterable)
function
: 用于处理每个元素的函数。iterable
: 要处理的可迭代对象,如列表、元组等。def func(i):
# 获取立方
return i ** 3
num_list = [i for i in range(1, 6)]
map_ = map(func, num_list)
print(map_, type(map_))
print(list(map_))
# <map object at 0x00000264F209B640> <class 'map'>
# [1, 8, 27, 64, 125]
num_list = [i for i in range(1, 6)]
map_ = map(lambda x: x ** 3, num_list)
print(map_, type(map_))
print(list(map_))
# <map object at 0x00000264F209B640> <class 'map'>
# [1, 8, 27, 64, 125]
def func():
age = 20
print("函数内局部作用域".center(20, "-"))
print(f"当前作用域内容:{locals()}")
print(f"全局作用域内容:{globals()}")
name = "bruce"
func()
print("全局作用域".center(20, "-"))
print(f"当前作用域内容:{locals()}")
print(f"全局作用域内容:{globals()}")
# ------函数内局部作用域------
# 当前作用域内容:{'age': 20}
# 全局作用域内容:{'name': 'bruce', 'func': <function func at 0x00>}
# -------全局作用域--------
# 当前作用域内容:{'name': 'bruce', 'func': <function func at 0x00>}
# 全局作用域内容:{'name': 'bruce', 'func': <function func at 0x00>}
iterator
)和生成器(generator
)range
range_ = range(10)
print(range_, type(range_))
# range(0, 10) <class 'range'>
iter
list_ = [i for i in range(10)]
iter_ = iter(list_)
print(iter_, type(iter_))
# <list_iterator object at 0x000002216550B640> <class 'list_iterator'>
next
list_ = [i for i in range(3)]
iter_ = iter(list_)
print(next(iter_))
print(next(iter_))
print(next(iter_))
# 0
# 1
# 2
eval
(慎用)# 有返回结果
res = eval("12+13")
print(res)
# 25
# 交互型 有返回结果
res = eval("input('name:>>>')")
print(res)
# name:>>>bruce
# bruce
# 交互型 没返回结果
name = "bruce"
res = eval("print(f'name:>>>{name}')")
print(res)
# name:>>>bruce
# None
exec
(慎用)exec
和eval
比较
eval
:返回表达式的值;计算单一表达式,不适用于执行多个语句excel
:只返回None
;可执行多个语句和代码块# 没有返回结果
res = exec("result = 12+13")
print(f"res:{res}, result:{result}")
# res:None, result:25
# 执行多条语句
username_password = """
username = input('username:>>>')
password = input('password:>>>')
"""
exec(username_password)
print(f"username:{username},passord:{password}")
# username:>>>bruce
# password:>>>000
# username:bruce,passord:000
# 执行代码块
func_str = """
def func():
print('It is func.')
func()
"""
exec(func_str)
# It is func.
# 导入模块
module_input = """
import random
import time
"""
exec(module_input)
print(random.randint(1,2))
print(time.localtime().tm_year)
# 2
# 2023
compile
(慎用)filename
是代码的文件名,如果代码不来自文件,则使用一个字符串。# 执行eval
content = "12+13"
compile_ = compile(content, "", mode="eval")
res = eval(compile_)
print(res)
# 25
# 执行代码块exec
func_str = """
def func():
print('It is func.')
func()
"""
compile_ = compile(func_str, "", mode="exec")
exec(compile_)
# It is func.
input
age = input("age:>>>")
print(age, type(age))
# age:>>>18
# 18 <class 'str'>
print
sep
:单个输出中,多单参数之间的间隔内容,默认是空格end
:再输出结尾的内容,默认是换行# sep
print("apple", "orange", "banana", sep=", ")
# apple, orange, banana
# end
print("name:bruce", end="\t")
print("age:18")
# name:bruce age:18
hash
计算给定对象的哈希值# set_ = {"da", 12, "ab", "1", 1}
# print(set_)
# for i in set_:
# print(hash(i))
#
int_ = 1
str_ = "a"
tuple_ = (1,)
list_ = [1]
print(hash(int_)) # 1
print(hash(str_)) # -6644214454873602895
print(hash(tuple_)) # -5718621942318842139
print(hash(list_)) # 报错,列表不能
set_ = {"apple", 18}
print(set_)
for data in set_:
print(hash(data))
# 第一次运行结果
# {18, 'apple'}
# 18
# -2441579320494278381
# 第二次运行结果
# {'apple', 18}
# 3900157648609508282
# 18
hash
值计算都不一样,我们还可以看出来,集合内的排序是按照hash
值从大到小排序的open
)、导入模块__import__
open
:用于打开一个文件, 创建一个文件句柄# 文件操作
f = open('01.txt',mode='r',encoding='utf8')
f.read()
f.close()
# 导入模块
module_name = input("time module name:>>>").strip()
time = __import__(module_name)
print(time.localtime().tm_year)
# time module name:>>>time
# 2023
help
、查看内置属性dir
# help():函数用于查看函数或模块用途的详细说明
print(help(str))
# 在pycharm按住ctrl点击int也可以查看详细说明
# dir():查看对象内置属性和方法
print(help(dict))
# 在pycharm按住ctrl点击dict也可以查看内置属性和方法
callable
对象是否可被调用
False:不可被调度
True:可被调度
int_ = 1
print(callable(int_)) # False
def func():
return None
print(callable(func)) # True