1.数学运算
round(2.3333,2)
2.33
pow(2,3)
8
pow(2,3,3)
2
max(1,2,3,1)
3
#执行字符串中的表达式,类型转换
eval('3+4')
7
str1 = "['p','y','t','h','o','n']"
type(str1)
str
eval(str1)
[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
type(eval(str1))
list
列表推导式
[x for x in str1 if x.isalpha()]
['p', 'y', 't', 'h', 'o', 'n']
x=1
y=1
def func1():
x=3
y=4
print(locals())
num1 = eval('x+y',locals())
print(num1)
num2 = eval('x+y',globals())
print(num2)
func1()
{'y': 4, 'x': 3}
7
2
2.类型转换
str(555)
#转换为字符串
'555'
list(range(6))
#转换为列表
[0, 1, 2, 3, 4, 5]
tuple(range(5))
#元组
(0, 1, 2, 3, 4)
set(range(3))
#集合
{0, 1, 2}
dict(a=1,b=2,c=3)
#字典
{'a': 1, 'b': 2, 'c': 3}
bin(32)
# 转化为二进制
'0b100000'
oct(56)
# 转化为8进制
'0o70'
hex(32)
# 转化为十六进制
'0x20'
ord('a')
#转化为ASCLL编码
97
chr(65)
#转化为对应字符
'A'
bytes('哈哈'.encode('utf-8'))
#加密字符,便于在网络中传输或保存
b'\xe5\x93\x88\xe5\x93\x88'
bytes('哈哈'.encode('gbk'))
b'\xb9\xfe\xb9\xfe'
b'\xe5\x93\x88\xe5\x93\x88'.decode('utf-8')
#使用decode解密
'哈哈'
'哈哈'.encode('utf-8')
#也可以直接转换
b'\xe5\x93\x88\xe5\x93\x88'
3.序列操作
li = [1,2,3]
all(li)
#参数为可迭代对象,全为真返回true
True
li1 = [1,2,3,0]
all(li1)
#有一个为假,返回false
False
li2 = []
all(li2)
#迭代器为空,返回true
True
any(li2)
#有一个为真则返回true,否则返回为False
False
list1=[9,1,5,3,4,2]
sorted(list1)
#不会改变list1本身
[1, 2, 3, 4, 5, 9]
sorted(list1,reverse=True)
#reverse 翻转,返回一个倒序的序列
[9, 5, 4, 3, 2, 1]
list1
[9, 1, 5, 3, 4, 2]
list2 = ['a','b','d','h','A','D','C','F']
list2
['a', 'b', 'd', 'h', 'A', 'D', 'C', 'F']
sorted(list2)
['A', 'C', 'D', 'F', 'a', 'b', 'd', 'h']
sorted(list2,key=str.lower)
['a', 'A', 'b', 'C', 'd', 'D', 'F', 'h']
sorted(list2,key=lambda x:x.lower())
#自建函数
['a', 'A', 'b', 'C', 'd', 'D', 'F', 'h']
序列遍历
- zip(zip_longest)
- enumerate
- chanin
a=[1,2,3,4]
b=['a','b','c','d']
c=['o','p']
a,b,c
([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['o', 'p'])
zip(a,b)
<zip at 0x271c957b548>
c=zip(a,b)
list(c)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
from itertools import zip_longest
# 当值不够时用None填充
for x in zip_longest(a,c):
print(x)
(1, 'o')
(2, 'p')
(3, None)
(4, None)
for x in zip_longest(a,c,fillvalue=0):
print(x)
# fillvalue 指定填充的值
(1, 'o')
(2, 'p')
(3, 0)
(4, 0)
dict(zip_longest(a,c,fillvalue=0))
#可以直接转换为字典
{1: 'o', 2: 'p', 3: 0, 4: 0}
list1
[9, 1, 5, 3, 4, 2]
enumerate(list1)
<enumerate at 0x271c95743a8>
for x in enumerate(list1,2):
print(x)
#返回一个可迭代对象,索引和值,第二个参数指定索引开始的值
(2, 9)
(3, 1)
(4, 5)
(5, 3)
(6, 4)
(7, 2)
dict(enumerate(list1))
#直接转化为字典
{0: 9, 1: 1, 2: 5, 3: 3, 4: 4, 5: 2}
list3=[(1,2),(3,4),(5,6),(7,8)]
list3
[(1, 2), (3, 4), (5, 6), (7, 8)]
for n,(x,y) in enumerate(list3):
print(n,x,y)
#numerate只能返回两个值
0 1 2
1 3 4
2 5 6
3 7 8
for a,b in enumerate(list3):
print(a,b)
0 (1, 2)
1 (3, 4)
2 (5, 6)
3 (7, 8)
a=[1,2,3,4]
b=['a','b','c','d']
c=['o','p']
set1=[1,2,3,4,5,6]
a,b,c
([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['o', 'p'])
from itertools import chain
# 可以遍历不同的两个序列,长度不同,类型不同
for x in chain(a,set1):
print(x)
1
2
3
4
1
2
3
4
5
6