如何在Python中生成一副牌

时间:2014-01-11 18:57:47

标签: python

如何在Python中以列表格式最有效地生成52张卡片,以便列表如下所示:

['1 of Spades', '1 of Hearts', '1 of Clubs', '1 of Diamonds', '2 of Spades', '2 of Hearts'等。

3 个答案:

答案 0 :(得分:6)

我更喜欢以下代码,如Python Readability Counts

>>> faces = range(2,11) + ["King","Queen","Jack","Ace"]
>>> colour = ["Spades", "Hearts", "Clubs", "Diamonds"]
>>> from itertools import product
>>> ["{} of {}".format(*card) for card in product(faces, colour)]

答案 1 :(得分:2)

要以列表格式轻松(并有效)生成一副牌,您可以输入:

deck = [str(x)+y for x in range(1,14) for y in ["S","H","C","D"]]

-

当你print(deck)时,你会得到这样的输出:

['1S', '1H', '1C', '1D', '2S', '2H', '2C', '2D', '3S', '3H', '3C', '3D'.....

-

例如,要将输出从"3C"更改为"3 of Clubs",请更改

["S","H","C","D"][" of Spades"," of Hearts"," of Clubs"," of Diamonds"]

-

这会使您的列表看起来像:['1 of Spades', '1 of Hearts', '1 of Clubs', '1 of Diamonds', '2 of Spades', '2 of Hearts'.....等等。

-

注意:最初的例子可能是最短的例子......

答案 2 :(得分:0)

>>> suits = ['spades', 'hearts', 'diamonds', 'clubs']
>>> faces = ['ace'] + range(2, 11) + ['jack', 'queen', 'king']
>>> deck = ['%s of %s'%(f, s) for f in faces for s in suits]