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]
# 创建内嵌列表 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以内偶数列表 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]]
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?