首页 > 编程语言 > 详细

python学习笔记8-列表、集合、字典推导式

时间:2019-05-02 00:05:03      阅读:194      评论:0      收藏:0      [点我收藏+]
# 1.列表推导式
a = [x**2 for x in range(5)]
a
# [0, 1, 4, 9, 16]
b = [x for x in a if x % 2 == 0]
b
# [0, 4, 16]
‘‘‘
等价于下面的for循环
b = []
for x in a:
    if x % 2 == 0:
        b.append(x)
‘‘‘

# 2.集合推导式
# 与列表推导式用法一致
L=[java,c++,python,ruby,php,None]
unique_length = {len(x) for x in L if x is not None}
unique_length
# {3, 4, 6}

# 3.字典推导式
dict1 = {a:b for a, b in zip(range(5),L) if len(b)>3}
dict1
# {0: ‘java‘, 2: ‘python‘, 3: ‘ruby‘}

# 4.嵌套的列表推导式
matrix = [[1,2,3],[4,5,6],[7,8,9]]
L1 = [x for l in matrix for x in l ]
L1
# [1, 2, 3, 4, 5, 6, 7, 8, 9] 
L2 = [[l[i] for l in matrix ] for i in range(len(matrix[0]))]
L2
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# 实现矩阵转置

 

python学习笔记8-列表、集合、字典推导式

原文:https://www.cnblogs.com/babysteps/p/python_note_8.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!