雖然python是一個(gè)易入門的語言,但是很多人依然還是會(huì)問到底怎么樣學(xué) Python 才最快,答案當(dāng)然是實(shí)戰(zhàn)各種小項(xiàng)目,只有自己去想與寫,才記得住規(guī)則。本文寫的是 10 個(gè)極簡(jiǎn)任務(wù),初學(xué)者可以嘗試著自己實(shí)現(xiàn);本文同樣也是 10段代碼,Python 開發(fā)者也可以看看是不是有沒想到的用法。
1、重復(fù)元素判定
以下方法可以檢查給定列表是不是存在重復(fù)元素,它會(huì)使用 set() 函數(shù)來移除所有重復(fù)元素。
- 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、分塊
給定具體的大小,定義一個(gè)函數(shù)以按照這個(gè)大小切割列表。
- 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、壓縮
這個(gè)方法可以將布爾型的值去掉,例如(False,None,0,“”),它使用 filter() 函數(shù)。
- 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 循環(huán)來遍歷某個(gè)列表,同樣我們也能枚舉列表的索引與值。
- 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、解包
如下代碼段可以將打包好的成對(duì)列表解開成兩組不同的元組。
- array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
- transposed = zip(*array)
- print(transposed)
- # [('a', 'c', 'e'), ('b', 'd', 'f')]
6、展開列表
該方法將通過遞歸的方式將列表的嵌套展開為單個(gè)列表。
- 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、 列表的差
該方法將返回第一個(gè)列表的元素,且不在第二個(gè)列表內(nèi)。如果同時(shí)要反饋第二個(gè)列表獨(dú)有的元素,還需要加一句 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、 執(zhí)行時(shí)間
如下代碼塊可以用來計(jì)算執(zhí)行特定代碼所花費(fèi)的時(shí)間。
- 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
該算法會(huì)打亂列表元素的順序,它主要會(huì)通過 Fisher-Yates 算法對(duì)新列表進(jìn)行排序:
- 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、 交換值
不需要額外的操作就能交換兩個(gè)變量的值。
- 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]
以上,是我簡(jiǎn)單列舉的十個(gè)python極簡(jiǎn)代碼,拿走即用,希望對(duì)你有所幫助!
原文鏈接:https://www.toutiao.com/a7041029007101592097/