内容:一些python常见的基础的语法。
目录
一、单星号与双星号(*与**)
https://www.cnblogs.com/omg-hxy/p/9081177.html
在形参前面加上“*”与“”“**”,称为动态参数
1.1 任意多参数
加“*”时,函数可接受任意多个参数,全部放入一个元祖中(注意是元组,其内容不可变更)
def F(*args):
print(args)
F(123,"456")
# (123, '456')
1.2 字典
加“**”时,函数接受参数时,返回为字典
def F(**kwargs):
print(kwargs)
F(k1=123,k2="456")
# {'k1': 123, 'k2': '456'}
1.3 动态参数实际例
def F(p,*args,**kwargs):
print(p)
print(args)
print(kwargs)
F(11,"abc",[789],k1=123,k2="456")
# 11
# ('abc', [789])
# {'k1': 123, 'k2': '456'}
上面这些参数,分别表示参数,动态参数,与字典
def F(*args):
print(args)
li = [11,22,33,44]
F(li)
F(*li)
# ([11, 22, 33, 44],)
# (11, 22, 33, 44)
这里分别把li这个list,第一次F(li)作为动态参数中的一个参数考虑,第二次作为F(*li)将整个list中的内容作为一个动态参数考虑。
函数中F(*li)前面加*的含义就是,告诉函数li的地位与输入参数的地位相同,li整个作为一个参数输入。
def F(**kwargs):
print(kwargs)
li = {"k1":1,"k2":2}
F(k=li)
F(**li)
# {'k': {'k2': 2, 'k1': 1}}
# {'k2': 2, 'k1': 1}
F(k=li)则li作为字典的一项,F(**li)则整个li作为字典的内容。**就是告诉函数,**后面的值整个为字典,而不是字典的一部分。
二、if __name__ == "__main__":
https://blog.csdn.net/yjk13703623757/article/details/77918633/
通俗的理解__name__ == '__main__'
:
- 假如你叫小明.py,在朋友眼中,你是小明
(__name__ == '小明')
; - 在你自己眼中,你是你自己
(__name__ == '__main__')
。 - 当.py文件被直接运行时,
if __name__ == '__main__'
之下的代码块将被运行; - 当.py文件以模块形式被导入时,
if __name__ == '__main__'
之下的代码块不被运行。
三、python三种括号() [] {}
https://blog.csdn.net/zhuhai__yizhi/article/details/77866293
3.1 ()元组
代表tuple元祖数据类型,元祖是一种不可变序列。创建方法很简单,大多数时候都是小括号括起来的。
1 >>> tup = (1,2,3)
2 >>> tup
3 (1, 2, 3)
4 >>> () #空元祖
5 ()
6 >>> 55,#一个值的元祖
7 (55,)
3.2 [] list
可变序列
1 >>> list('Python')
2 ['P', 'y', 't', 'h', 'o', 'n']
3.3 花括号{}dict
唯一内建的映射类型。字典中的值没有特殊的顺序,但都是存储在一个特定的键(key)下。键可以是数字、字符串甚至是元祖。
1 >>> dic = {'jon':'boy','lili"':'girl'}
2 >>> dic
3 {'jon': 'boy', 'lili"': 'girl'}
四、函数后->
https://www.python.org/dev/peps/pep-3107/
https://stackoverflow.com/questions/14379753/what-does-mean-in-python-function-definitions
函数注释,These are function annotations covered in PEP 3107. Specifically, the ->
marks the return function annotation. ->
专门表示函数return值的注释。
Examples:
>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules':
... return 1/2*m*v**2
...
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}
Annotations are dictionaries, so you can do this:
>>> '{:,} {}'.format(kinetic_energy(20,3000),
kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'
You can also have a python data structure rather than just a string:
>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'}
>>> def f()->rd:
... pass
>>> f.__annotations__['return']['type']
<class 'float'>
>>> f.__annotations__['return']['units']
'Joules'
>>> f.__annotations__['return']['docstring']
'Given mass and velocity returns kinetic energy in Joules'
Or, you can use function attributes to validate called values:
def validate(func, locals):
for var, test in func.__annotations__.items():
value = locals[var]
try:
pr=test.__name__+': '+test.__docstring__
except AttributeError:
pr=test.__name__
msg = '{}=={}; Test: {}'.format(var, value, pr)
assert test(value), msg
def between(lo, hi):
def _between(x):
return lo <= x <= hi
_between.__docstring__='must be between {} and {}'.format(lo,hi)
return _between
def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
validate(f, locals())
print(x,y)
Prints
>>> f(2,2)
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>
五、python下划线
https://www.cnblogs.com/hester/articles/4936603.html
https://www.cnblogs.com/skying555/p/6169110.html
用于指出特殊变量/方法(方法是类中的函数)
- object # public 变量表示public
- __object__ # special, python system use, user should not define like it 前后双下划线,表示系统调用
- __object # private (name mangling during runtime) 前双下划线,表示private,只在运行时调用
- _object # obey python coding convention, consider it as private 前单下划线,表示private,不能用from module import *导入
核心风格:避免用下划线作为变量名的开始。
六、%用法
https://www.jb51.net/article/136766.htm
6.1 取余数
模运算
>>> 7%2
1
# -*- coding: utf-8 -*-
'''
python读取文件,偶数行输出一个文件,奇数行输出一个文件
'''
def fenhang(infile,outfile,outfile1):
infopen = open(infile,'r',encoding='utf-8')
outopen = open(outfile,'w',encoding='utf-8')
outopen1 = open(outfile1, 'w', encoding='utf-8')
lines = infopen.readlines()
i = 0
for line in lines:
i += 1
if i % 2 == 0:
outopen.write(line)
else:
outopen1.write(line)
infopen.close()
outopen.close()
fenhang("源文件路径","偶行数文件路径","奇行数文件路径")
6.2 字符串格式化
https://www.cnblogs.com/xxby/p/5571620.html
Python的字符串格式化有两种方式:%格式符方式,format方式
%[(name)][flags][width].[precision]typecode
(name)为命名
flags可以有+,-,' '或0。+表示右对齐。-表示左对齐。' '为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填充。
width表示显示宽度
precision表示小数点后精度
(name) 可选,用于选择指定的key
a = "%(name)s-----%(age)d "%{'name':'xx','age':20}
print(a)
执行结果:
xx-----20
占位,+,右对齐,-,左对齐
b = "%(name)+10s————————%(age)-10d————————"%{'name':'xx','age':20}
print(b)
执行结果:
xx————————20 ————————
空格,右对齐
0,用0填充空白处
c = "------%(year) d******%(age)010d "%{'year':2016,'age':-20}
print(c)
执行结果:
------ 2016******-000000020
七、数组的维度
我们必须对python数组的维度和形状有一个直观和清晰的认识,这样用起来的时候才会得心应手。
7.1 二维数组的形状
http://www.runoob.com/numpy/numpy-array-manipulation.html
import numpy as np
a = np.arange(8)
print ('原始数组:')
print (a)
print ('\n')
b = a.reshape(4,2)
print ('修改后的数组:')
print (b)
输出,即为shape(4,2)的数组
原始数组:
[0 1 2 3 4 5 6 7]
修改后的数组:
[[0 1]
[2 3]
[4 5]
[6 7]]
即,shape中从后往前,参数位置靠后,则为横轴,例如2靠后,则最小的中括号中为两个元素,理解为横轴
倒数第二个为纵轴,例如其中为4,则每个纵轴上有4个元素
再例如:
a = np.arange(8).reshape(2,4)
则输出为:
原数组:
[[0 1 2 3]
[4 5 6 7]]
7.2 三维数组
>>> import numpy as np
>>> a = np.arange(24).reshape(2,3,4)
>>> print(a)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
依然shape中的参数越靠后,则为横轴,例如其中的4,
倒数第二个为纵轴,如其中的3,行数为3
在倒数一个为channel数,2,则两个channel。
这时,几何意义就是,第一个channel数,第二个row数,第三个col数
7.3 多维度数组
依然shape中的参数越靠后,则离得越近,越在一个中括号之中:
>>> b=np.arange(120).reshape(2,3,4,5)
>>> print(b)
[[[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[ 10 11 12 13 14]
[ 15 16 17 18 19]]
[[ 20 21 22 23 24]
[ 25 26 27 28 29]
[ 30 31 32 33 34]
[ 35 36 37 38 39]]
[[ 40 41 42 43 44]
[ 45 46 47 48 49]
[ 50 51 52 53 54]
[ 55 56 57 58 59]]]
[[[ 60 61 62 63 64]
[ 65 66 67 68 69]
[ 70 71 72 73 74]
[ 75 76 77 78 79]]
[[ 80 81 82 83 84]
[ 85 86 87 88 89]
[ 90 91 92 93 94]
[ 95 96 97 98 99]]
[[100 101 102 103 104]
[105 106 107 108 109]
[110 111 112 113 114]
[115 116 117 118 119]]]]