彩虹然

rainbow-ran

Python3.7之列表生成式

a = [i for i in range(10)]
b = range(10)
print(a)
print(type(a))
print(b)
print(type(b))

'''
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'list'>
range(0, 10)
<class 'range'>
'''

一、两层循环,可以构成全排列

m = [a + b + c for a in '123' for b in '123' for c in '123']
print(m)

# ['111', '112', '113', '121', '122', '123', '131', '132', '133', '211', '212', '213', '221', '222', '223', '231', '232', '233', '311', '312', '313', '321', '322', '323', '331', '332', '333']

二、使用if

c = [i for i in range(10) if i > 5]
print(c)

# [6, 7, 8, 9]

三、使用 if …else …

注意顺序和用法

d = [i if i > 5 else i*10 for i in range(10)]
print(d)

#输出结果: [0, 10, 20, 30, 40, 50, 6, 7, 8, 9]

四、随机取3个不重复的数字

m = [(a, b, c) for a in '123' for b in '123' for c in '123' if a != b and b != c and a != c]
print(m)

# [('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
posted @ 2020-01-16 16:18  彩虹然  阅读(490)  评论(0编辑  收藏  举报