导读:本文用于Python易忽略语法及特性的自我提醒,避免忘记。
字符串是可以用 [] 访问的,和C不同。
string = "asdfgh"# slicer []: [fron:to:step]print(string[0]) => 'a'print(string[:]) => 'asdfgh'print(string[0:3]) => 'asd'print(string[-6:-1]) => 'asdfg'print(string[-6:5]) => 'asdfg'print(string[0:6:2]) => 'adg'字符串/数字/元组 是 不可变对象;列表/字典/集合 是 可变对象。
xxxxxxxxxxli = [1,2,3,4,5]it = iter(li)# 调用方式1for i in it: print(i) => 1,2,3,4,5# 调用方式2while True: try: print(next(it)) except StopIteration: break是一种特殊的迭代器,其返回值是一个迭代器。
xxxxxxxxxxdef generator(): a = b = 1 yield a yield b while True: yield a+b a, b = b, a+bit = generator()times = 10while True: try: if times > 0: print(next(it)) times -= 1 else: break except StopIteration: break*args 把接收到的参数变为元组
**kwargs 把接收到的关键字参数转变为字典
xdef function1(a, *args): print(type(args)) => tuple print(args) => 2,3,4function1(1,2,3,4)def function2(a, **args): print(type(args)) =>dict print(args) => {'asd':123, 'qwe':456}function2(1,asd=123,qwe=456)# *号后的参数是关键字参数,必须用xx=xxxx的方式传入def function3(a, *, b, c): passfunction3(1, b=1, c=1)# Python3.8:/号前的参数是位置参数,只能根据位置传入def function3(a, b, /, c, d): pass# function3(1, b=2, 3) 错误调用function3(1, 2, 3)xxxxxxxxxxsumfx = lambda arg1, arg2: arg1 + arg2print(sumfx(1,2))xxxxxxxxxx"format:%.2f%s%5d"%(12.345,'asd',1) => 'format:12.34asd 1''str{}{}'.format(1,'qwe') => 'str1qwe''str{a}{qwe}'.format(a='gg', qwe='sss') => strggsss'str{a}{}{qwe}{}'.format(1,2,a='gg', qwe='sss') => strgg1sss2xxxxxxxxxx# 20以内偶数的平方的列表[i**2 for i in range(20) if i%2 == 0]xxxxxxxxxxa = 1 if k in ['asd', 'qwe'] else 2把一个可迭代对象的每项用一个函数作用,返回新的可迭代对象
xxxxxxxxxx# map(func, iterable)it = map(lambda arg1: return arg1**2 ,[1,2,3])for i in it: print(i) => 1 4 9xxxxxxxxxx# enumerate(*args, **kwargs)it = enumerate(['a', 'b', 'c', 'd', 'e'])for i in it: print(i) => (0,'a') (1,'b') ... (4, 'e')for i, v in it: print('index={},value={}'%(i,v))xxxxxxxxxx# zip(iterable1, iterable2)it = enumerate(['a', 'b', 'c'], ['q', 'w', 'e'])for i,v in it: print(i,v, sep='@') => a@q b@w c@exxxxxxxxxx# sorted(iterable1, *, key, reverse)print(sorted([5,4,3,2,1], reverse=True))xxxxxxxxxxfor i in reversed(range(10)): print(i) => 9,8,7,...0