您好,登錄后才能下訂單哦!
這篇“Python的列表推導式是什么”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Python的列表推導式是什么”文章吧。
1.普通
[expression for target in iterable]
2.帶條件
[expression for target in iterable if condition]
3.嵌套
[expression for target1 in iterable1 if condition1 for target2 in iterable2 if condition2 ... for targetN in iterableN if conditionN]
x = [1, 2, 3, 4, 5] x = [i * 2 for i in x] print(x) # [2, 4, 6, 8, 10]
y = [i for i in range(10)] print(y) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 獲取矩陣第二列 matrix = [ [1, 2, 3], [3, 5, 6], [7, 8, 9] ] col2 = [row[1] for row in matrix] print(col2) # [2, 5, 8]
# 獲取矩陣主對角線元素 matrix = [ [1, 2, 3], [3, 5, 6], [7, 8, 9] ] diag = [matrix[i][i] for i in range(len(matrix))] print(diag) diag2 = [matrix[i][len(matrix) - i - 1] for i in range(len(matrix))] print(diag2) # [1, 5, 9] # [3, 5, 7]
# 創(chuàng)建內(nèi)嵌列表 a = [[0] * 3 for i in range(3)] print(a) a[1][1] = 5 print(a) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # [[0, 0, 0], [0, 5, 0], [0, 0, 0]]
# 20以內(nèi)偶數(shù)列表 b = [i for i in range(20) if i % 2 == 0] print(b) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 篩選F開頭的單詞 words = ['Great', 'FishC', 'Brilliant', 'Excellent', 'Fantistic'] res = [word for word in words if word.startswith('F')] print(res) # ['FishC', 'Fantistic']
# 展開二維列表 matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] flatten = [col for row in matrix for col in row ] print(flatten) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
等價于
flatten = [] for row in matrix: for col in row: flatten.append(col)
# 笛卡爾積 fulljoin = [x + y for x in '12345' for y in 'abcde'] print(fulljoin) # ['1a', '1b', '1c', '1d', '1e', '2a', '2b', '2c', '2d', '2e', '3a', '3b', '3c', '3d', '3e', '4a', '4b', '4c', '4d', '4e', '5a', '5b', '5c', '5d', '5e']
ans = [[x, y] for x in range(10) if x % 2 == 0 for y in range(10) if y % 3 == 0] print(ans) # [[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]
以上就是關于“Python的列表推導式是什么”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關的知識內(nèi)容,請關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。