之所以讀書、行路,就是希望我們能夠不斷地享受高級快樂
伊始
很多喜歡使用 Python,是因為它的簡便、易用且功能強大。但把python當作C來寫的人也屢見不鮮,我個人較為著迷于用一行代碼解決一些復雜的問題,可以參考我之前的文章一行有效python代碼。
當然,Python 中的大多數(shù)一行代碼都是用 map() 和列表生成式編寫的。今天,再和大家一起看幾個一行python代碼就能搞定的問題。
list中的元素類型轉換
- 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]
矩陣轉置
- Desc
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
==>
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
-
How
結合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!