utf-8编码
在py文件首行写入:# -*- coding:utf-8 -*-
all()函数
all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
元素除了是 0、空、None、False 外都算 True。
如果iterable的所有元素不为0、’’、False或者iterable为空,all(iterable)返回True,否则返回False;
注意:空元组、空列表返回值为True,这里要特别注意。
>>> all(['a', 'b', 'c', 'd']) # 列表list,元素都不为空或0
True
>>> all(['a', 'b', '', 'd']) # 列表list,存在一个为空的元素
False
>>> all([0, 1,2, 3]) # 列表list,存在一个为0的元素
False
>>> all(('a', 'b', 'c', 'd')) # 元组tuple,元素都不为空或0
True
>>> all(('a', 'b', '', 'd')) # 元组tuple,存在一个为空的元素
False
>>> all((0, 1, 2, 3)) # 元组tuple,存在一个为0的元素
False
>>> all([]) # 空列表
True
>>> all(()) # 空元组
True
ord(c)函数
参数c为单字符,返回对应的 ASCII 数值
>>>ord('a')
97
>>> ord('b')
98
>>>ord('9')-48
9
*print(values, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)中参数介绍
1 *values : 表示要打印的值
表示任何多个无名参数, 各个值之间用‘,’(逗号隔开),打印出来各个值之间用空格隔开
2 sep=’ ‘: 表示当输入多个打印的值时,各个值之间分割方式, 默认空格,可以自定义,例如
print('a', 'b', 'c')
#输出为:
a b c
#(中间默认用空格隔开)
#当设置sep = ‘\n’时上面代码结果为:
a
b
c
3 end=‘\n’: 打印完后结束符号,默认换行,可以设置为 ‘\t’, ’ ’ 等等, 可以自己定义,如下:
print('CSDN')
print('is good')
#输出为:
CSDN
is good
#默认换行,如果设置:end=' '
print('CSDN', end=' ')
print('is good')
#则输出为:
CSDN is good
zip()
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
打印当前文件目录
import os
print(os.getcwd()) # D:\ShiQing\python_code\data_process
print(os.path.abspath(os.path.dirname(__file__))) # D:\ShiQing\python_code\data_process
print(os.path.abspath(__file__)) # D:\ShiQing\python_code\data_process\test3.py
-> 用法
用于指定函数参数或返回值的类型
例如:
def add(x, y) -> int:
return x+y
这里面,指定了函数的返回值为int类型。
def f(a:str, b:str = 'b') -> str:
pass
#打印函数属性
print(f.__annotations__) #{'a': <class 'str'>, 'b': <class 'str'>, 'return': <class 'str'>}
表示返回值类型应该为str。(在此也可以不限于数据类型,也可以是具体字符串比如说‘b Number’,甚至是任何表达式等等)
python是动态语言,传入参数和返回参数没有参数类型,在python3中加入了类型注解,方便了解返回值的类型,实际上没有用,你返回的类型和参数注解写的不一致也不会报错。
如果参数或返回值是list、dict等,可引入模块typing:
from typing import List, Dict, Tuple
参考:https://www.cnblogs.com/cwp-bg/p/7825729.html
collection.defaultdict()
用于构建key为空的字典
from collections import defaultdict
s=[('yellow',1),('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
# d=defaultdict(int)
d=defaultdict(list) #构建列表字典,可指定value的类型,如list、int、str等
print(d) #defaultdict(<class 'list'>, {})
for k,v in s:
d[k].append(v)
print(d) #defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
a=sorted(d.items())
print(a) #[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
b=sorted(d)
print(b) #['blue', 'red', 'yellow']
用法类似于dict.setdefault()。