python列表推导式

列表推导式

#普通生成列表
l1 = []
for i in range(10):
    l1.append(i)
print(l1)



# 高级的列表推导
l1=[i for i in range(10)]
print(l1)

l1=[i**2 for i in range(10)]
print(l1)


# 输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
name_list = ['chen', 'python', 'nick', 'rock']
print([name if name == 'chen' else name + 'sb' for name in name_list])
#输出:
['chen', 'pythonsb', 'nicksb', 'rocksb']
posted @ 2019-08-13 20:20  豆瓣酱瓣豆  阅读(227)  评论(0编辑  收藏  举报