我的目标是在python中创建一副牌的列表。我正在使用itertools.product。以下代码创建了正确的列表,但是,它仅在for循环中有效。
如何在for循环之外存储和使用列表?
打印圈内循环列表:
#CARDS#
import itertools
rank = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]
suit = ["h", "d", "s", "c"]
for card in itertools.product(rank, suit):
card_deck = card[0] + card[1]
print card_deck
输出:
2h 2d 2s 2c 3h 3d 3s 3c 4h 4d 4s 4c 5h 5d 5s 5c 6h 6d 6s 6c 7h 7d 7s 7c 8h 8d 8s 8c 9h 9d 9s 9c Th Td Ts Tc Jh Jd Js Jc Qh Qd Qs Qc Kh Kd Ks Kc Ah Ad As Ac
打印循环 列表
for card in itertools.product(rank, suit):
card_deck = card[0] + card[1]
print card_deck
输出:
AC
答案 0 :(得分:2)
问题在于,当您完成循环后,card_deck
仍然具有最后一个值。如果你想要所有的值,那么你需要将它们存储在某个地方...也许是一个列表:
card_deck = []
for card in itertools.product(rank, suit):
card_deck.append(card[0] + card[1])
print card_deck
这看起来像列表理解的真正好候选人:
card_deck = [card[0] + card[1] for card in itertools.product(rank, suit)]