之所以讀書纵寝、行路攒岛,就是希望我們能夠不斷地享受高級快樂
伊始
很多喜歡使用 Python赖临,是因?yàn)樗暮啽恪⒁子们夜δ軓?qiáng)大灾锯。但把python當(dāng)作C來寫的人也屢見不鮮兢榨,我個(gè)人較為著迷于用一行代碼解決一些復(fù)雜的問題,可以參考我之前的文章一行有效python代碼顺饮。
當(dāng)然吵聪,Python 中的大多數(shù)一行代碼都是用 map() 和列表生成式編寫的。今天兼雄,再和大家一起看幾個(gè)一行python代碼就能搞定的問題吟逝。
list中的元素類型轉(zhuǎn)換
- Example
list(map(int, ['1', '2', '3']))
list(map(float, ['1', 2, '3.0', 4.0, '5', 6]))
- Output
[1, 2, 3]
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
int的位數(shù)和
- Desc
12345 => 1+2+3+4+5 = 15
- How
sum_of_digits = lambda x : sum(map(int, str(x)))
print(sum_of_digits(12345))
- Output
15
二維數(shù)組的扁平化
- Desc
[[1, 2, 3], [4, 5], [6], [7, 8], [9]] ==> [1, 2, 3, 4, 5, 6, 7, 8, 9]
- How
datas = [[1, 2, 3], [4, 5], [6], [7, 8], [9]]
flattened_list = [item for data in datas for item in data]
矩陣轉(zhuǎn)置
- Desc
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
==>
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
-
How
結(jié)合zip
使用列表生成式
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[list(i) for i in zip(*A)]
交換dict
的key和value
- How
d = {'one': 1, 'three': 3}
staff = {i:j for j, i in d.items()}
- Output
{1: 'one', 3: 'three'}
Not End
Have a nice day!