# Github星数4600+，每30秒学会一个Python小技巧，爱了爱了

Python交流扣扣裙：797403929

## 1. List：all_equal

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


## 2. List：all_unique

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


## 3. List：bifurcate

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'] ]


## 4. 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]


## 5. 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]


## 6. Math：digitize

def digitize(n):
return list(map(int, str(n)))


digitize(123) # [1, 2, 3]


## 7. 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]


## 8. Math：clamp_number

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


## 9. String：byte_size

def byte_size(string):
return len(string.encode('utf-8'))


byte_size('😀') # 4
byte_size('Hello World') # 11


## 10. Math：gcd

from functools import reduce
import math

def gcd(numbers):
return reduce(math.gcd, numbers)


gcd([8,36,28]) # 4


Python交流扣扣裙：797403929

• 0
点赞
• 0
评论
• 0
收藏
• 打赏
• 扫一扫，分享海报

11-03 16

11-30 280
03-12 3万+
10-23 697
03-05 4万+
11-21 4万+

¥2 ¥4 ¥6 ¥10 ¥20

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