python鲜为人知的小技巧
1.字典合并 以d2为基准更新d1
d1={"a":1}
d2={"b":2,"a":10}
d1.update(d2)
print(d1)
print(dict(d1.items()|d2.items()))
2.for else
a=[1,2,3,4,5]
for i in a:
if i==0:
print(i)
break
else:
print("did not break out of for loop")
3.函数的链式写法
def product(a,b):
return a*b
def add(a,b):
return a+b
b=True
print((product if b else add)(5,2))
4.简易版word count,找出列表中多次出现的元素
import collections
a=[1,2,3,2,3,12,3,22,3,2,2,2]
collections.Counter(a).most_common()
#max(list(),key=)
a=[1,2,3,2,3,12,3,22,3,2,2,2]
max(set(a),key=a.count)
5.转至二维数组
original=[['a','b'],['c','d'],['e','f']]
transpose=zip(*original)
print(list(transpose))
6.反转list
a=['a','b','c']
b=a[::-1]
print(a)
print(b)
7.反转字符串
a='i love you baby'
b=a[::-1]
print(a)
print(b)