本次给大家推荐一个学习这些技巧的很好的资源“30-seconds-of-python”,所有技巧方法只要30秒就能get到,完全可以利用业务时间不断积累。下面赶紧来看一下。
作者:xiaoyu,数据爱好者
来源:Python数据科学出品(ID:PyDataScience)
项目地址:
https://github.com/30-seconds/30-seconds-of-python
00 内容目录
下面是30秒学Python的整个目录,分为几大板块:List、Math、Object、String、Utility,以下是整理的思维脑图。
我挑选了10个实用并很有意思的方法分享给大家,其余的感兴趣可以自行学习。
01 List:all_equal
[1:]
和 [:-1]
来比较给定列表的所有元素。def all_equal(lst):
return lst[1:] == lst[:-1]
all_equal([1, 2, 3, 4, 5, 6]) # False
all_equal([1, 1, 1, 1]) # True
02 List:all_unique
True
,否则 False
set()
去重,比较它和原列表的长度。
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
all_unique(x) # True
all_unique(y) # False
03 List:bifurcate
filter
的元素是True
,那么对应的元素属于第一个组;否则属于第二个组。enumerate()
基于filter
元素到各组。
def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
]
bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])
# [ ['beep', 'boop', 'bar'], ['foo'] ]
04 List:difference
def difference(a, b):
_b = set(b)
return [item for item in a if item not in _b]
difference([1, 2, 3], [1, 2, 4]) # [3]
05 List:flatten
def flatten(lst):
return [x for y in lst for x in y]
flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6, 7, 8]
06 Math:digitize
map()
函数结合int
完成转化def digitize(n):
return list(map(int, str(n)))
digitize(123) # [1, 2, 3]
07 List:shuffle
from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
08 Math:clamp_number
num
钳在由a和b边界值规定的范围中。num
落尽范围内,返回num
;否则,返回范围内最接近的数字。
def clamp_number(num,a,b):
return max(min(num, max(a,b)),min(a,b))
clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1
09 String:byte_size
string.encode('utf-8')
解码给定字符串,返回长度。
def byte_size(string):
return len(string.encode('utf-8'))
byte_size('?') # 4
byte_size('Hello World') # 11
10 Math:gcd
reduce()
和math.gcd
在给定列表上实现。
from functools import reduce
import math
def gcd(numbers):
return reduce(math.gcd, numbers)
gcd([8,36,28]) # 4
以上就是30秒学python的各种小技巧。怎么样,对于一些常见操作是不是有了一些新的启发,除此之外,还有很多其它技巧可以慢慢学习,希望对各位读者有所帮助。