文章目录
- 常用内置函数
- 0. input:
- 1. 进制转换:
- 2. 大小堆:
- 3. list用法:
- 4. dict用法:
- 5. set用法:
- 6. 判断字符串是字母、数字、大小写:
- 7. all与any
- 8. 字符串转字节数组
- 9. 字节与ASCII码相互转换
- 10. 加减乘除相关
- 11. eval函数:
- 12. filter函数:
- 13. map函数:
- 14. reduce函数:
- 15. format函数
- 16. isinstance函数
- 17. hasattr函数:
- 18. glob函数:
- 19. strip函数:
- 20. split函数:
- 21. range函数:
- 22. reversed函数:
- 23. join函数:
- 24. sort函数:
- 25. zip函数
- 26. 制表符/换行符
- 常用库函数
常用内置函数
0. input:
# input() 函数接受一个标准输入数据,返回为 string 类型。
a = '123456'
b = input("username:")
if b == a : # 如果b的输入数据等于a存储的数据,打印”right“
print("right")
else: # 否则打印”wrong“
print("wrong")
# 1)
line = input().split(' ')
# 2)
import sys
first_line = sys.stdin.readline().rstrip().split(' ')
1. 进制转换:
# bin()函数返回一个整数int或者长整数long int的二进制表示。 10->2
print( bin(10) ) # 0b1010
print( bin(133) ) # 0b10000101
# oct() 函数将一个整数转换成八进制字符串。 10->8
print( oct(10) ) # 0o12
print( oct(255) ) # 0o377
print( oct(-6655) ) # -0o14777
# hex() 函数用于将一个整数转换为十六进制数。返回一个字符串,以0x开头。 10->16
print(hex(1)) # 0x1
print(hex(-256)) # -0x100
print(type(hex(-256))) #<class 'str'>
# int() 函数用于将一个字符串或数字转换为整型。 n->10
print(int()) # 不传入参数时,得到结果0
print(int(0.5)) # 去掉小数部分,得到结果0
print(int(3)) # 得到结果3
print(int('0xa',16)) # 十六进制数“0xa”转换成十进制整数,得到结果10
print(int('00010',2)) # 二进制数“00010”转换成十进制整数,得到结果2
print(int('0o377', 8))
2. 大小堆:
import heapq
# 默认小顶堆
heap = []
# 压入
heapq.heappush(heap, 3)
# 弹出
top = heapq.heappop(heap)
# 取最大的n个
a, b = heapq.nlargest(2, array)
# 取最小的n个
a, b = heapq.nsmallest(2, array)
# 用99替换堆顶元素
top = heapq.heappushpop(heap, 99)
3. list用法:
list = [a, b, c, d]
# 尾部添加元素
list.append(a)
# 尾部添加另一个list的多个值
list1.extend(list2) #直接打印list1,就是合起来的结果
# 将某个对象插入指定idx
list.insert(idx, a)
# 删除元素
# 1)通过idx实现
del list[2]
# 2)通过idx实现,并返回所删除的值
pop_val = list.pop(-1) # 默认最后一个
# 3)直接删除list中的值
list.remove(val)
# 统计某元素出现在次数
list.count(a)
# 从list中找出某个值的第一idx
list.index(a)
# 排序
list.sort(cmp=None, key=None, reverse=False) #reverse=True 降序
# 如random = [(2, 2), (3, 4), (4, 1), (1, 3)], 按第二位数排序
# print(sorted(random, key=lambda s: s[1], reverse=True))
# 逆序
list.reverse()
# 比较两list是否相等
import operator
operator.eq(ls1, ls2)
# 最大、最小
max(list)
min(list)
# 元祖转list
a = (1 , 3, 5)
b = list(a)
4. dict用法:
# 初始化
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
# 判断key是否存在
dict.has_key(key)
# 返回key和val的元组
dict.items()
# 返回key
dict.keys()
# 返回vals
dict.values()
# 删除某个key及对应val
del dict[key]
dict.pop(key) # 返回删除key对应的val
dict.popitem() # 返回并删除字典中的最后一对键和值。
# dict()函数用来将元组/列表转换为字典格式。
print(dict(a='a', b='b', t='t')) # 返回:{'b': 'b', 'a': 'a', 't': 't'}
print(dict( [ ('one',1),('two',2),('three',3) ] ) ) # 可迭代对象方式来构造字典 返回:{'two': 2, 'one': 1, 'three': 3}
print(dict(zip(["1","2","3"],["a","b","c"]))) # 映射函数方式来构造字典 返回:{'2': 'b', '3': 'c', '1': 'a'}
5. set用法:
# set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
b = set([1,2,3,4,5])
# 添加元素
b.add(10)
# 删除元素
b.remove(10)
c = set([2,4,6,8,10])
print(b & c) # 交集,得到结果为{2, 4}
print(b | c) # 并集,得到结果为{1, 2, 3, 4, 5, 6, 8, 10}
print(b - c) # 差集,得到结果为{1, 3, 5}
6. 判断字符串是字母、数字、大小写:
字符串.isalnum() 所有字符都是数字或者字母,为真返回 Ture,否则返回 False。
字符串.isalpha() 所有字符都是字母,为真返回 Ture,否则返回 False。
字符串.isdigit() 所有字符都是数字,为真返回 Ture,否则返回 False。
字符串.islower() 所有字符都是小写,为真返回 Ture,否则返回 False。
字符串.isupper() 所有字符都是大写,为真返回 Ture,否则返回 False。
字符串.istitle() 所有单词都是首字母大写,为真返回 Ture,否则返回 False。
字符串.isspace() 所有字符都是空白字符,为真返回 Ture,否则返回 False。
7. all与any
# all()函数用于判断给定的参数中的所有元素是否都为TRUE,如果是返回 True,否则返回 False。
# 元素除了是 0、空、None、False 外都算 True;空元组、空列表返回值为True。
print( all( [0.1,1,-1] ) ) # 返回 True
print( all( (None,1) ) ) # 返回 False(其中一个元素为None)
print( all( [0,1,-1] ) ) # 返回 False(其中一个元素为0)
print( all( [" ","a",""] ) ) # 返回 False(第三个元素为空)
print( all( ())) # 返回 True
# any() 函数用于判断给定的参数是否全部为False,是则返回False,如果有一个为True,则返回True。
# 元素除了是 0、空、False, None外都算 TRUE。
# 参数全部不为 0、空、FALSE
print(any("-45")) # True
print(any(["-45"])) # True
print( any( ("0","ab","") ) ) # True(注意:第一个参数0加了双引号,表示为一个字符串)
# # 参数全部为 0、空、False、None
print( any( (0,"") ) ) # False
print( any( (0,"",False, None) ) ) # False
8. 字符串转字节数组
# bytearray()方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256(即0-255)。
# 即bytearray()是可修改的二进制字节格式。
b = bytearray("abcd",encoding="utf-8")
print(b[0]) # 返回数字97,即把“abcd”的“a"对应的ascii码打印出来了
b[0] = 99 # 把字符串第一个字节修改为99(即对应字母为“c”)
print(b) # 返回:bytearray(b'cbcd')---第一个字节a已被修改为c
9. 字节与ASCII码相互转换
# chr()函数用一个范围在range(256)内(即0~255)的整数作参数,返回一个对应的ASCII数值。
# 把数字98在ascii码中对应的字符打印出来
print( chr(98) ) # 返回:b
# ord()函数是chr()的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值.
# 如果所给的 Unicode 字符超出了定义范围,则会引发一个 TypeError 的异常。
print(ord('b')) # 返回:98
10. 加减乘除相关
# divmod()函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(商x,余数y)
print( divmod(5,2) ) # 返回:(2, 1)
print( divmod(5,1) ) # 返回:(5, 0)
print( divmod(5,3) ) # 返回:(1, 2)
# / 与 //的区别
print(5 / 3) # 熵
print(5 // 3) # 熵的最大整数
# pow与math.pow
# 通过内置的方法直接调用
print( pow(2,3) ) # 8
# 导入math模块调用,math模块会把参数转化成float
import math
print(math.pow(2, 3)) # 8.0
# round() 方法返回浮点数x的四舍五入值
print( round(4.3)) # 只有一个参数时,默认保留到整数 # 4
print( round(2.678,2)) # 保留2位小数 # 2.68
print(int(2.678 * 100) / 100) # 保留2位小数(不四舍五入) 2.67
print( round(5/3,3)) # 运算表达式并保留3位小数 # 1.667
11. eval函数:
# eval() 函数用来执行一个字符串表达式,并返回表达式的值。
print(eval("3 * 2")) # 6
x = 7
print(eval('3 + x')) # 10
12. filter函数:
# filter()用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,可用list()来转换为列表。
# 注意: filter()接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,
# 然后返回True或 False,最后将返回 True 的元素放到新列表中。
res = filter(lambda n:n>5, range(10)) # 过滤掉0-9中不符合n>5的数据
print(list(res)) #[6, 7, 8, 9]
13. map函数:
# map()接收函数f和list,并通过把函数f依次作用在list的每个元素上,得到一个新的list并返回。
res = map(lambda n: n*2,[0,1,2,3,4,5]) # 使用 lambda 匿名函数
print(list(res)) # [0, 2, 4, 6, 8, 10]
14. reduce函数:
# reduce() 函数会对参数序列中元素进行累积。在Python3 ,reduce()被放置在functools模块里,如果想要使用它,需要先引入functools模块。
import functools
a = functools.reduce(lambda x,y: x+y, [1, 2, 3])
print(a) # 6
b = functools.reduce(lambda x,y:x+y,range(10))
print(b) # 45 , 即从0加到9
15. format函数
# format()是一种格式化字符串的函数 ,基本语法是通过 {} 和 : 来代替以前的 % 。
# format 函数可以接受不限个参数,位置可以不按顺序。
print( "{}{}".format('a','1') )
print('name:{b}, old:{a}'.format(a = '23', b = 'zs')) # name:zs, tex:23
16. isinstance函数
# isinstance() 函数来判断一个对象是否是一个已知的类型,返回布尔值。类似 type(),区别:type不考虑继承关系。
a = 2
print(isinstance(a,int)) # True
print(isinstance(a,str)) # False
print(isinstance(a,(str,tuple,dict))) # False
print(isinstance(a,(str,tuple,int))) # 是元组其中的一个则返回True
17. hasattr函数:
# hasattr() 函数用于判断对象是否包含对应的属性。如果对象有该属性返回 True,否则返回 False。
class t:
a = 1
b = 2
c = 3
p = t()
print(hasattr(p,'a')) # True
print(hasattr(p,'b')) # True
print(hasattr(p,'x')) # False
18. glob函数:
# glob()函数用于查看路径下特定的文件格式
from glob import glob
root_path = '.'
file_name = glob(root_path + "/*.py")
print(file_name)
19. strip函数:
# strip() 删除 string 字符串指定字符, lstrip(), rstrip();默认是空格
str = " 88888888this is string example....wow!!!8888888 "
print(str.strip()) # 88888888this is string example....wow!!!8888888
str = "88888888this is string example....wow!!!8888888"
print(str.strip('8')) # this is string example....wow!!!
print(str.lstrip('8')) # this is string example....wow!!!8888888
print(str.rstrip('8')) # 88888888this is string example....wow!!!
20. split函数:
# split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
s = "abc def ghi"
print(s.split()) # ['abc', 'def', 'ghi']
print(s.split(' ', 1)) # ['abc', 'def ghi']
21. range函数:
# range() 函数可创建一个整数列表,一般用在 for 循环中。语法:range(start, stop, step)
for b in range(10, 0, -2): # 步长为-2
print(b) # 打印10,8,6,4,2
22. reversed函数:
# reversed() 函数返回一个反转的迭代器。 reversed(seq)要转换的序列,可以是 tuple, string, list 或 range。
a = list(reversed((1, 2, 3))) # 元组
s = ','.join([str(it) for it in a])
print(s)
23. join函数:
# join()函数连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
#a = ','.join(seq)
s = [1, 2, 3, 4]
a = ','.join([str(it) for it in s])
print(a) # '1,2,3'
24. sort函数:
# sort()函数对所有可迭代的对象进行排序(默认升序)操作
# 对字典进行排序
dict = {23:42,1:0,98:46,47:-28}
print( sorted(dict) ) # 只对key排序 # [1, 23, 47, 98]
print( sorted(dict.values())) # 只对val排序 # [-28, 0, 42, 46]
print( sorted(dict.items()) ) # 默认按key进行排序 # [(1, 0), (23, 42), (47, -28), (98, 46)]
print( sorted(dict.items(),key=lambda x:x[1]) ) # 用匿名函数实现按value进行排序 # [(47, -28), (1, 0), (23, 42), (98, 46)]
# # 对字典进行倒序
print( sorted(dict.items(), key=lambda x:x[1], reverse=True)) # [(98, 46), (23, 42), (1, 0), (47, -28)]
25. zip函数
# zip()函数将对象中对应的元素打包成一个个元祖,然后使用list输出列表。使用zip(*)可以解压
a = [1,2,3]
b = [4,5,6]
c = list(zip(a, b)) # [(1, 4), (2, 5), (3, 6)]
print(c) # {1: 4, 2: 5, 3: 6}
26. 制表符/换行符
# \n 为换行符;\t 为制表符
print("test: \n a")
# test
# a
print("test: \t a")
# test: a
常用库函数
1.os函数
#查看当前路径
cur_path = os.path.abspath(os.path.dirname(__file__))
root_path = os.path.split(cur_path)[0]
#将当前路径加入系统变量中
sys.path.append(cur_path)
#判断某路径是否存在
os.path.exists('home/dir')
#扩展到使用者目录
root = '~/.torch/models'
root = os.path.expanduser(root) #root :'/home/wangdepeng/.torch/models'
2.pyclipper函数
- 作用:用于多边形的切割
- 参考:Python之pyclipper使用
3. glob函数
- 作用:找到文件夹下指定格式的所有文件
#找到./data文件夹下所有.jpg的图片
import glob
img_dir = './data'
img_names = glob.glob(img_dir + '/*jpg')
print(img_names)
4. open函数
- 作用:读写文件
- 参考:使用 with open() as 读写文件
#读
with open('/path/to/file', 'r') as f:
print(f.read()) #一次性读取全部文件
#for line in f.readlines(): #按行读取文件
#print(line.strip()) # 把末尾的'\n'删掉
#写
with open('E:\python\python\test.txt', 'w') as f:
f.write('Hello, python!')
5. random函数
import random
# random.random()方法用于生成一个0到1的随机浮点数:0<=n<1.0
print(random.random())
# random.uniform(a,b):用于生成一个指定范围内的随机浮点数
print(random.uniform(10, 20))
# random.randint(a,b):用于生成一个指定范围内的整数
print(random.randint(10, 20))
# random.randrange(start, stop, step]):从指定范围内,按指定基数递增的集合中获取一个随机数
print(random.randrange(10, 20, 2))
# random.choice(seq):随机从seq序列中取出一个值
print(random.choice(["JGood","is","a","handsome","body"]))
print(random.choice(("Tuple","list","Dict")))
# random.shuffle(seq):打乱seq顺序
seq = ["pyhton","is","powerful","simple","and so on..."]
random.shuffle(seq)
print(seq)
# random.sample(seq, k): 从seq中随机取出k个值
print(random.sample(seq, 2))
6. 异常
# 将可能引发错误的代码放在try-except代码块,将依赖于try代码块成功执行的代码放在else中
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)