列表生成式

# 列表生成式

L = [i * i for i in range(1, 11) if i % 2 ==0]
print(L)

# 两层循环

L1 = [ i + j for i in "ABC" for j in 'HKJ']
print(L1)

# 两层循环类似于嵌套循环

for i in 'ABC':
    for j in "HKJ":
        print(j+i)

# 用列表生成式列出当前目录下的所有文件和目录名

import os
L3 = [d for d in os.listdir('.')]
print(L3)

# 列表生成式也可以使用两个变量来生成list

german_english = {'Huhn':'Dog', 'Katze':'Cat', 'Vogel':'Bird'}
L4 = [g + ':' + e for g, e in german_english.items()]
print(L4)

# exercise

L5 = ['Hello', 'World', 18, 'Apple', None]
L6 = [s.lower() for s in L5 if isinstance(s, str)]
print(L6)

你可能感兴趣的:(列表生成式)