我正在尝试创建所有可能的扑克牌组合。所以,我跑了:
import itertools as it
ranks = (2,3,4,5,6,7,8,9,10,'Jack','Queen','King','Ace')
suits = ('Spades', 'Clubs', 'Hearts', 'Diamonds')
for i in zip(ranks, it.repeat(suits, 14)):
print(i)
得到了:
(2, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(3, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(4, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(5, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(6, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(7, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(8, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(9, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
(10, ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
('Jack', ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
('Queen', ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
('King', ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
('Ace', ('Spades', 'Clubs', 'Hearts', 'Diamonds'))
从这个元组列表中获取['2 of Spades', '2 of Clubs', '2 of Hearts', ...]
的有效方法是什么?
我目前的方法是:
cards = []
for card in zip(ranks, it.repeat(suits, 14)):
rank, suits = card
for suit in suits:
cards.append("{} of {}".format(rank, suit))
有更好的方法吗?它是什么?
答案 0 :(得分:3)
我认为你不需要迭代工具。列表理解将正常工作:
cards = [ "{} of {}".format(r, s) for r in ranks for s in suits ]