对于Python中的list再理解

1.列表包含着表达式:

squares = [x**2 for x in range(10)]
#输出结果为:
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2.列表嵌套着for语句如下实例,列表还包含着元组。

squares = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
#输出结果为
squares =[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

对于2中的实例还可以如下写法:

combs = []
for x in [1, 2, 3]:
    for y in [3, 1, 4]:
        if x != y:
            combs.append((x, y))

print(combs)

3.列表中嵌套着复杂的表达式例如函数等。如下实例

实例1.
vec = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
examp = [num for ele in vec for num in ele]
print(examp)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

实例2.
freshFruit = ['  Orange', 'Apple ', '  Banana  ']
exam1 = [indentFruit.strip() for indentFruit in freshFruit]
#输出结果
print(exam1)
['Orange', 'Apple', 'Banana']

实例3.
from math import pi
[str(round(pi, i)) for i in range(1, 6)]
#round()函数表示返回pi的小数位数
#输出结果为:
['3.1', '3.14', '3.142', '3.1416', '3.14159']

猜你喜欢

转载自blog.csdn.net/qq_34138155/article/details/81156149