雖然python是一個易入門的語言,但是很多人依然還是會問到底怎么樣學 Python 才最快,答案當然是實戰各種小專案,只有自己去想與寫,才記得住規則,本文寫的是 10 個極簡任務,初學者可以嘗試著自己實作;本文同樣也是 10段代碼,Python 開發者也可以看看是不是有沒想到的用法,
1、重復元素判定
以下方法可以檢查給定串列是不是存在重復元素,它會使用 set() 函式來移除所有重復元素,
def all_unique(lst):
return len(lst)== len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True
2、分塊
給定具體的大小,定義一個函式以按照這個大小切割串列,
from math import ceil
def chunk(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))
chunk([1,2,3,4,5],2)
# [[1,2],[3,4],5]
3、壓縮
這個方法可以將布爾型的值去掉,例如(False,None,0,“”),它使用 filter() 函式,
def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34])
# [ 1, 2, 3, 'a', 's', 34 ]
4、 使用列舉
我們常用 For 回圈來遍歷某個串列,同樣我們也能列舉串列的索引與值,
list = ["a", "b", "c", "d"]
for index, element in enumerate(list):
print("Value", element, "Index ", index, )
# ('Value', 'a', 'Index ', 0)
# ('Value', 'b', 'Index ', 1)
#('Value', 'c', 'Index ', 2)
# ('Value', 'd', 'Index ', 3)
5、解包
如下代碼段可以將打包好的成對串列解開成兩組不同的元組,
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed)
# [('a', 'c', 'e'), ('b', 'd', 'f')]
6、展開串列
該方法將通過遞回的方式將串列的嵌套展開為單個串列,
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result = []
result.extend(
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
7、 串列的差
該方法將回傳第一個串列的元素,且不在第二個串列內,如果同時要反饋第二個串列獨有的元素,還需要加一句 set_b.difference(set_a),
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
difference([1,2,3], [1,2,4]) # [3]
8、 執行時間
如下代碼塊可以用來計算執行特定代碼所花費的時間,
import time
start_time = time.time()
a = 1
b = 2
c = a + b
print(c) #3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)
# ('Time: ', 1.1205673217773438e-05)
9、 Shuffle
該演算法會打亂串列元素的順序,它主要會通過 Fisher-Yates 演算法對新串列進行排序:
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]
10、 交換值
不需要額外的操作就能交換兩個變數的值,
def swap(a, b):
return b, a
a, b = -1, 14
swap(a, b) # (14, -1)
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
以上,是我簡單列舉的十個python極簡代碼,拿走即用,希望對你有所幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/385573.html
標籤:其他
