Python基础系列-列表解析(list comprehension)

版权声明:如需转载,请注明转载地址。 https://blog.csdn.net/oJohnny123/article/details/81910866

列表解析(list comprehension)

 

A2 = [i for i in A1 if i in A0]

其实等同于

A2 = []
for i in A1:
    if i in A0:
        A2.append(i)

所以就可以玩出很多花来了,包含列表的交集、差集等等。

代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Created by liaoyangyang1 on 2018/2/28 下午9:26.
"""

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = [i for i in A1 if i in A0]
A3 = [A0[s] for s in A0]
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]

 执行结果:

/Users/liaoyangyang/crc/codes-python/LearnPython/venv/bin/python /Users/liaoyangyang/crc/codes-python/LearnPython/test.py
A0:{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
A1:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
A2:[]
A3:[1, 3, 2, 5, 4]
A4:[1, 2, 3, 4, 5]
A5:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6:[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Process finished with exit code 0

 

上一篇:Python进阶-算法-插入排序


下一篇:Python基础系列-copy和deepcopy