Python开发中的高级技巧

列表推导式

print(chars=[c for c in ‘python’ ])
[ ‘p’ ,‘y’ ,‘t’ ,‘h’ , ‘o’ ,‘n’ ]

字典推导式

dict1 = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5}
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
print(double_dict1)
{‘a’: 2, ‘b’: 4, ‘c’: 6, ‘d’: 8, ‘e’: 10}

集合推导式

set1 = {1,2,3,4}
double_set = {i*2 for i in set1}
print(double_set)
{8, 2, 4, 6}

合并字典

x = {‘a’:1,‘b’:2}
y = {‘c’:3, ‘d’:4}
z = {**x, **y}
print(z)
{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

复制列表

nums = [1,2,3]
print(nums[::])
[1, 2, 3]

反转列表

nums = [1,2,3]
print(nums[::-1])
[3, 2, 1]

变量交换

a,b = 1, 2
a ,b = b,a
print(a)
print(b)
2
1

高级拆包

a, *b = 1,2,3
print(a)
1
print(b)
[2, 3]
或者
a, *b, c = 1,2,3,4,5
print(a)
1
print(b)
[2, 3, 4]
print©
5

函数返回多个值(其实是自动packing成元组)然后unpacking赋值给4个变量

def f():
return 1, 2, 3, 4

a, b, c, d = f()
print(a)
1
print(d)
4

列表合并成字符串

aa=" ".join([“I”, “Love”, “Python”])
print(aa)
‘I Love Python’

没有使用 field from
def dup(n):
for i in range(n):
yield i
yield i

使用yield from

def dup(n):
    for i in range(n):
    yield from [i, i]

for i in dup(3):
    print(i)

0
0
1
1
2
2

in 与 or的替换(效果是一样的)

if x == 1 or x == 2 or x == 3:
    pass

if x in (1,2,3):
    pass

字典代替多个ifelse

def fun(x):
    if x == 'a':
        return 1
    elif x == 'b':
        return 2
    else:
        return None
等价于:
def fun(x):
    return {"a": 1, "b": 2}.get(x)

有下标索引的枚举

for i, e in enumerate(["a","b","c"]):
     print(i, e)

0 a
1 b
2 c

列表中出现次数最多的元素

nums = [1,2,3,3]
print(max(nums, key=nums.count))
3

或者
from collections import Counter
print(Counter(nums).most_common()[0][0])
3

判断对象类型,可指定多个类型

print(isinstance(a, (int, str)))
True

类似的还有字符串的 startswith,endswith

print( “http://foofish.net”.startswith((‘http’,‘https’)))
True
print(“https://foofish.net”.startswith((‘http’,‘https’)))
True

strrepr 区别

print(str(datetime.now()))
‘2018-11-20 00:31:54.839605’
print(repr(datetime.now()))
‘datetime.datetime(2018, 11, 20, 0, 32, 0, 579521)’

前者对人友好,可读性更强,后者对计算机友好,支持 obj == eval(repr(obj))

使用装饰器

def makebold(f):
      return lambda: "<b>" + f() + "</b>"

def makeitalic(f):
    return lambda: "<i>" + f() + "</i>"

@makebold
@makeitalic
def say():
    return "Hello"

say()
<b><i>Hello</i></b>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值