案例一:
# coding=utf-8
test_list = [i for i in range(1, 11)]
print(test_list)
输出结果如下:
该方式通过for循环遍历,将range(1,11)生成的10个元素存入该列表中
案例二:
# coding=utf-8
test_list = [i*i for i in range(1, 11)]
print(test_list)
输出结果如下:
对列表中每个元素进行平方操作
案例三:
# coding=utf-8
test_list = [i * i for i in range(1, 11) if i % 2 == 0]
print(test_list)
输出结果如下:
对range生成的数字先判断是否为偶数,如果是偶数,则进行平方操作
案例四 :
# coding=utf-8
test_list = [i + j for i in 'python' for j in 'PYTHON']
print(test_list)
输出结果如下:
对两组字符串分别遍历,然后进行字符串拼接操作
类似如下操作:
# coding=utf-8
# test_list = [i + j for i in 'python' for j in 'PYTHON']
# print(test_list)
new_list = []
for i in 'python':
for j in 'PYTHON':
k = i + j
new_list.append(k)
print(new_list)
两种方式输出结果相同