用列表生成式三行代码生成一副扑克牌

155 阅读1分钟

今天刚学了python的列表生成式,就用来试一下

color=['黑桃','红心','草花','方块']
num=[2,3,4,5,6,7,8,9,10,'J','Q','K','A']
list=[f'{i}{j}'for i in color for j in num]+['小王','大王']
print(list)

其实用列表生成式还可以用if语句,比如说

#打印不含数字2的扑克牌
color=['黑桃','红心','草花','方块']
num=[2,3,4,5,6,7,8,9,10,'J','Q','K','A']
list=[f'{i}{j}'for i in color for j in num if j!=2]+['小王','大王']
print(list)

用这种方法生成列表很简便