Python列表元组和字典解析式

以下内容基于Python 3x

列表解析式List comprehensive

解析式是一种语法糖,其优点有提高效率,减少工作量,减少出错,简化代码,提高可读性。

语法格式如下:

[expression for item in iterable if condition]

返回一个新的列表

查看几个例子即可明白:

# Example
# 迭代0-9至res1
res1 = [x for x in range(10)]
# 迭代0-9并且能整除2的结果至res2
res2 = [x for x in range(10) if x % 2 == 0]
# 迭代0-19能整除2和3的结果至res3
res3 = [x for x in range(20) if x % 2 == 0 and not x % 3]
print(res1, res2, res3, sep="
")

# Result
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[0, 6, 12, 18]

进阶:

# Example 1
res = []
for x in range(3):
    for y in range(3):
        res.append(x + y)
print(res)

# 使用列表解析式的 Example 1
res1 = [x + y for x in range(3) for y in range(3)]
print(res1)

# Example 2
res2 = []
for x in range(3):
    for y in range(3):
        if not (x % 2 or y % 2):
            res2.append(x + y)
print(res2)

# Example 3
res3 = []
for x in range(3):
    for y in range(3):
        if x % 2 == 0:
            if y % 2 == 0:
                res3.append(x + y)
print(res3)

# 使用列表解析式的 Example 2 and Example 3
res4 = [x + y for x in range(3) for y in range(3) if not (x % 2 or y % 2)]
print(res4)

打印九九乘法表:

处理好样式格式化问题,其实就很好理解

# Example 4
for x in range(1, 10):
    for y in range(1, x + 1):
            print("{} * {} = {}	".format(y, x, y * x), end='')
    print()

# 使用列表解析式的 Example 4
[print("{} * {} = {}	{}".format(y, x, y * x, '
' if x == y else ''), end='') for x in range(1, 10) for y in range(1, x + 1)]

集合解析式Set comprehensive

语法格式:

{expression for item in iterable if condition}

返回一个新的集合

Example:

res = {x for x in range(5)}
print(res)

字典解析式Dict comprehensive

语法格式:

{key: value for item in iterable if condition}

返回一个新的字典

Example:

res = {chr(x): x for x in range(65, 70)}
print(res)

# Result 
{'A': 65, 'B': 66, 'E': 69, 'D': 68, 'C': 67}

总结

列表解析式在Python2中引入,集合与字典解析式在Python3中引入,后来同样也支持了Python2.7。

一般来说,应该多应用解析式,简短、高效。如果看到一个解析式过于复杂,则可以考虑将其层层拆解为等价的for循环表达形式,然后去理解和应用。

原文地址:https://www.cnblogs.com/ioops/p/14313399.html