Github星数4600+,30秒学会一个Python小技巧!
天作之程
共 2846字,需浏览 6分钟
·
2021-05-11 11:55
![](https://filescdn.proginn.com/61fdacbdf587744da08bd578bae76e55/29408763b64fbd730d606aa777ef40db.webp)
链接:
https://github.com/30-seconds/30-seconds-of-python
![](https://filescdn.proginn.com/4ba3f96e653c8c8f9afc5315501f4996/28f00293a202d183d61024ef82e992d0.webp)
![](https://filescdn.proginn.com/5164232889d0e6ed61e964fa2c3c051f/6511a855f81af38b12cc03b7ee53c9cd.webp)
[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
True
,否则 Falsedef 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
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]
]
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]
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]
def digitize(n):
return list(map(int, str(n)))
digitize(123) # [1, 2, 3]
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]
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
def byte_size(string):
return len(string.encode('utf-8'))
byte_size('😀') # 4
byte_size('Hello World') # 11
from functools import reduce
import math
def gcd(numbers):
return reduce(math.gcd, numbers)
gcd([8,36,28]) # 4
评论