Python语法简要概览
很久没用过Python了,熟悉一下用法准备ms。
输入和输出
>>> var=input('input:')
input:sjdf asdkjf 123 adsf ;dfa--..
>>> print(var)
sjdf asdkjf 123 adsf ;dfa--..
暂时理解input()读入一行数据,且可以加入提示信息。 读入一个整数:
s = input('birth: ')
birth = int(s)
基本注意事项
# 注释某行中其后的内容。
缩进代替C系列语言中的大括号。
大小写敏感。
字符串可用''或""包裹, \可用于转义。\n\t等
r''表示''内部的字符串默认不转义
'''表示多行输入
>>> print(r'\\\t\\')
\\\t\\
>>> print('''hi
... hi
... hi
... hello,py
... ''')
hi
hi
hi
hello,py
空值是一个特殊的值,用None表示。None不能理解为0,因为0是有意义的,而None是一个特殊的空值。
用全部大写的变量名表示常量。
三种除法,//地板除,/整除,得到浮点数,%取余。
在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。
ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符。
格式化:
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
有意思的数据类型
list
>>> fruits = ['apple', 'banana', 'orange']
>>> fruits
['apple', 'banana', 'orange']
>>> len(fruits)
3
>>> fruits[1]
'banana'
>>> fruits[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
- 倒数
>>> fruits[-1]
'orange'
>>> fruits[-2]
'banana'
>>> fruits[-6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
append()
insert(1, 'hi')
pop()
list中的元素类型可以不同
tuple
不可更改的list,声明用()
当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来。
t = (1)定义的是自然数1,要定义成tuple需要加‘,’,规则。
t = ('a', 'b', ['A', 'B'])其中的list是可变的。
dict
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
>>> d['Adam'] = 67
>>> d['Adam']
67
- 判断是否存在dict中的两个方法
一是通过in判断key是否存在;
二是通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value。
>>> 'Thomas' in d
False
>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1
删除用pop('Bob')。
set
s = set([1, 2, 3])
s.add(4)
s.remove(4)
可以对集合进行&和|操作。
判断&循环
if
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
for...in
可打印list、tuple中的数据。
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
sum = 0
for x in range(101):
sum = sum + x
print(sum)
while
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
break&continue
同C系列语言
函数
内置函数
- abs()
- int()
- max()
- hex()
- isinstance()
函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”:
>>> a = abs # 变量a指向abs函数
>>> a(-1) # 所以也可以通过a调用abs函数
1
自定义函数
def my_abs(x):
if x >= 0:
return x
else:
return -x
- pass
什么都不做,作为占位符 - 返回多个值
在语法上,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值,所以,Python的函数返回多值其实就是返回一个tuple
函数参数
- 默认参数
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
- 可变参数
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
>>> nums = [1, 2, 3]
>>> calc(*nums)
14
*nums表示把nums这个list的所有元素作为可变参数传进去。
- 关键字参数
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
>>> person('Michael', 30)
name: Michael age: 30 other: {}
>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, city=extra['city'], job=extra['job'])
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,对kw的改动不会影响到函数外的extra
- 命名关键字参数
- 命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。
- 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了。
- 命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错
def person(name, age, *, city, job):
print(name, age, city, job)
>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer
def person(name, age, *args, city, job):
print(name, age, args, city, job)
def person(name, age, *, city='Beijing', job):
print(name, age, city, job)
>>> person('Jack', 24, job='Engineer')
Jack 24 Beijing Engineer
限定了kw中的关键字只能为city,job
参数组合
参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
支持递归
高级特性
切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L[0:3]
L[:3]
L[-2:]
L[-2:-1]
L[:10:2]
L[::5]
L[:]
迭代
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
... print(key)
...
a
b
c
>>> for k, v in d.items():
... print(k,v)
...
a 1
b 2
c 3
>>> for value in d.values():
... print(value)
...
1
2
3
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
列表生成式
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
>>> import os # 导入os模块,模块的概念后面讲到
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
生成器
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
小结
生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
把list、dict、str等Iterable变成Iterator可以使用iter()函数:
凡是可作用于for循环的对象都是Iterable类型;
凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
Python的for循环本质上就是通过不断调用next()函数实现的,例如:
for x in [1, 2, 3, 4, 5]:
pass
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
except StopIteration:
# 遇到StopIteration就退出循环
break
函数式编程
高阶函数
- 传入函数
def add(x, y, f):
return f(x) + f(y)
map/reduce
- map
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
- reduce
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) - 两者综合
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))
- filter
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 结果: ['A', 'B', 'C']
- sorted
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']