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)所以就可以玩出很多花来了,包含列表的交集、差集等等。
版权声明:如需转载,请注明转载地址。 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

 

目录
相关文章
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
634 2
|
开发者 Python
Python列表推导式:优雅与效率的完美结合
Python列表推导式:优雅与效率的完美结合
643 116
|
大数据 开发者 Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
554 109
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
645 119
|
开发者 Python
Python列表推导式:优雅与效率的完美融合
Python列表推导式:优雅与效率的完美融合
489 104
Python列表推导式:优雅与效率的艺术
Python列表推导式:优雅与效率的艺术
540 99
|
数据处理 Python
解锁Python列表推导式:优雅与效率的完美融合
解锁Python列表推导式:优雅与效率的完美融合
596 99
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
689 95
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
785 99
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术

推荐镜像

更多