我正在尝试漂亮地打印列表,但是不幸的是,我遇到了一些麻烦。因此,代码如下所示:
from pprint import pprint
deck = []
for s in ("CDHS"):
for v in ("A23456789TJQK"):
deck.append(v+s)
print(deck)
pprint(deck, width=20)
我正在尝试像这样打印套牌:
AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC
AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD
AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH
AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS
但是它是这样打印的:
['AC',
'2C',
'3C',
......
.....
请告诉我如何解决!谢谢
答案 0 :(得分:1)
尝试一下。您可以根据需要调整各种width
值。
>>> pp = pprint.PrettyPrinter(width=38, compact=True)
>>> pp.pprint(deck)
['AC', '2C', '3C', '4C', '5C', '6C',
'7C', '8C', '9C', 'TC', 'QC', 'JC',
'KC', 'AD', '2D', '3D', '4D', '5D',
'6D', '7D', '8D', '9D', 'TD', 'QD',
'JD', 'KD', 'AH', '2H', '3H', '4H',
'5H', '6H', '7H', '8H', '9H', 'TH',
'QH', 'JH', 'KH', 'AS', '2S', '3S',
'4S', '5S', '6S', '7S', '8S', '9S',
'TS', 'QS', 'JS', 'KS']
答案 1 :(得分:1)
懒惰的方式,只需要从嵌套循环中直接打印卡即可:
>>> for s in ("CDHS"):
... for v in ("A23456789TQJK"):
... print(v+s, end=' ')
... print()
...
AC 2C 3C 4C 5C 6C 7C 8C 9C TC QC JC KC
AD 2D 3D 4D 5D 6D 7D 8D 9D TD QD JD KD
AH 2H 3H 4H 5H 6H 7H 8H 9H TH QH JH KH
AS 2S 3S 4S 5S 6S 7S 8S 9S TS QS JS KS
更多Python方式,将您的牌组分为chunks和tabulate:
>>> from tabulate import tabulate # pip install tabulate
>>> from wimpy import chunks # pip install wimpy
>>> deck2 = chunks(deck, len("A23456789TQJK"))
>>> print(tabulate(deck2, tablefmt="plain"))
AC 2C 3C 4C 5C 6C 7C 8C 9C TC QC JC KC
AD 2D 3D 4D 5D 6D 7D 8D 9D TD QD JD KD
AH 2H 3H 4H 5H 6H 7H 8H 9H TH QH JH KH
AS 2S 3S 4S 5S 6S 7S 8S 9S TS QS JS KS