
點選上方“藍字”,發現更多精彩。
作者丨Fatos Morina
來源丨Python 技術
導讀
本文是 30 個極簡任務,初學者可以嘗試着自己實作;本文同樣也是 30 段代碼,Python 開發者也可以看看是不是有沒想到的用法。
本文是 30 個極簡程式設計任務,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) # Falseall_unique(y) # True
2 字元元素組成判定
檢查兩個字元串的組成元素是不是一樣的。
from collections import Counterdef anagram(first, second): return Counter(first) == Counter(second)anagram("abcd3", "3acdb") # True
3 字典預設值
通過 Key 取對應的 Value 值,可以通過以下方式設定預設值。如果 get() 方法沒有設定預設值,那麼如果遇到不存在的 Key,則會傳回 None。
d = {'a': 1, 'b': 2}print(d.get('c', 3)) # 3
4 位元組占用
下面的代碼塊可以檢查字元串占用的位元組數。
def byte_size(string):return(len(string.encode('utf-8')))byte_size('') # 4byte_size('Hello World') # 11
6 大寫第一個字母
以下代碼塊會使用 title() 方法,進而大寫字元串中每一個單詞的首字母。
s = "programming is awesome"print(s.title())# Programming Is Awesome
7 分塊
給定具體的大小,定義一個函數以按照這個大小切割清單。
from math import ceildef 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]
8 壓縮
這個方法可以将布爾型的值去掉,例如(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 ]
9 解包
如下代碼段可以将打包好的成對清單解開成兩組不同的元組。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]transposed = zip(*array)print(transposed)# [('a', 'c', 'e'), ('b', 'd', 'f')]
11 逗号連接配接
下面的代碼可以将清單連接配接成單個字元串,且每一個元素間的分隔方式設定為了逗号。
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming
12 元音統計
以下方法将統計字元串中的元音 (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) 的個數,它是通過正規表達式做的。
import redef count_vowels(str): return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))count_vowels('foobar') # 3count_vowels('gym') # 0
13 首字母小寫
如下方法将令給定字元串的第一個字元統一為小寫。
def decapitalize(string): return str[:1].lower() + str[1:]decapitalize('FooBar') # 'fooBar'decapitalize('FooBar') # 'fooBar'
14 展開清單
該方法将通過遞歸的方式将清單的嵌套展開為單個清單。
def spread(arg): ret = [] for i in arg: if isinstance(i, list): ret.extend(i) else: ret.append(i) return retdef deep_flatten(lst): result = [] result.extend( spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) return resultdeep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
15 清單的差
該方法将傳回第一個清單的元素,其不在第二個清單内。如果同時要回報第二個清單獨有的元素,還需要加一句 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]
16 元素頻率
下面的方法會根據元素頻率取清單中最常見的元素。
def most_frequent(list): return max(set(list), key = list.count)list = [1,2,1,2,3,2,1,4,2]most_frequent(list)
17 Try else
我們在使用 try/except 語句的時候也可以加一個 else 子句,如果沒有觸發錯誤的話,這個子句就會被運作。
try: 2*3except TypeError: print("An exception was raised")else: print("Thank God, no exceptions were raised.")#Thank God, no exceptions were raised.
18 合并兩個字典
下面的方法将用于合并兩個字典。
def merge_two_dicts(a, b): c = a.copy() # make a copy of a c.update(b) # modify keys and values of a with the once from b return ca={'x':1,'y':2}b={'y':3,'z':4}print(merge_two_dicts(a,b))#{'y':3,'x':1,'z':4}
在 Python 3.5 或更高版本中,我們也可以用以下方式合并字典:
def merge_dictionaries(a, b) return {**a, **b}a = { 'x': 1, 'y': 2}b = { 'y': 3, 'z': 4}print(merge_dictionaries(a, b))# {'y': 3, 'x': 1, 'z': 4}
19 将兩個清單轉化為字典
如下方法将會把兩個清單轉化為單個字典。
def to_dictionary(keys, values): return dict(zip(keys, values))keys = ["a", "b", "c"]values = [2, 3, 4]print(to_dictionary(keys, values))#{'a': 2, 'c': 4, 'b': 3}
往期推薦
1、如何用資料找到下一家獨角獸?2、數說第七次人口普查的結果,對于我們普通人有哪些重要的影響3、資料分析來诠釋"985/211廢物"的焦慮與失意