垂直打印列表列表

时间:2014-10-01 03:10:13

标签: python

我有一个列表列表,其中包含代表卡片中卡片的字符串。我需要垂直打印列表。

stacks = [['4C', 'QD', '9D', 'TD', 'JH', 'JD', '6C', 'AC', '3C', 'TS', 'TH'], ['AH', '2C', 'KD', '8C', '5C', '5H', '2D', '5D', '7C', 'AS', 'AD'], ['3S', 'KH', '3H', 'TC', 'QS', '4D', '7S', '7H', '9C', '4S'], ['JS', '7D', 'KC', 'QH', '6S', '6H', '8H', '8S', 'JC', '5S'], ['KS', '2S', 'QC', '4H', '6D', '9S', '2H', '8D', '3D', '9H']]

我需要它打印如下:

4C AH 3S JS KS
QD 2C KH 7D 2S

继续这样

3 个答案:

答案 0 :(得分:1)

您可以使用zip

stacks = [['4C', 'QD', '9D', 'TD', 'JH', 'JD', '6C', 'AC', '3C', 'TS', 'TH'], ['AH', '2C', 'KD', '8C', '5C', '5H', '2D', '5D', '7C', 'AS', 'AD'], ['3S', 'KH', '3H', 'TC', 'QS', '4D', '7S', '7H', '9C', '4S'], ['JS', '7D', 'KC', 'QH', '6S', '6H', '8H', '8S', 'JC', '5S'], ['KS', '2S', 'QC', '4H', '6D', '9S', '2H', '8D', '3D', '9H']]
stacks = zip(*stacks)
print stacks

<强>输出

[('4C', 'AH', '3S', 'JS', 'KS'), 
 ('QD', '2C', 'KH', '7D', '2S'), 
 ('9D', 'KD', '3H', 'KC', 'QC'), 
 ('TD', '8C', 'TC', 'QH', '4H'), 
 ('JH', '5C', 'QS', '6S', '6D'), 
 ('JD', '5H', '4D', '6H', '9S'), 
 ('6C', '2D', '7S', '8H', '2H'), 
 ('AC', '5D', '7H', '8S', '8D'), 
 ('3C', '7C', '9C', 'JC', '3D'), 
 ('TS', 'AS', '4S', '5S', '9H')]

答案 1 :(得分:1)

前两行比其他行长,因此请使用itertools.izip_longest()代替标准zip()来保留该数据。我使用了填充值'',用于不等长度列表中的缺失值。

from itertools import izip_longest

stacks = [['4C', 'QD', '9D', 'TD', 'JH', 'JD', '6C', 'AC', '3C', 'TS', 'TH'], ['AH', '2C', 'KD', '8C', '5C', '5H', '2D', '5D', '7C', 'AS', 'AD'], ['3S', 'KH', '3H', 'TC', 'QS', '4D', '7S', '7H', '9C', '4S'], ['JS', '7D', 'KC', 'QH', '6S', '6H', '8H', '8S', 'JC', '5S'], ['KS', '2S', 'QC', '4H', '6D', '9S', '2H', '8D', '3D', '9H']]

for row in izip_longest(*stacks, fillvalue=''):
    print ' '.join(row)

输出:

4C AH 3S JS KS
QD 2C KH 7D 2S
9D KD 3H KC QC
TD 8C TC QH 4H
JH 5C QS 6S 6D
JD 5H 4D 6H 9S
6C 2D 7S 8H 2H
AC 5D 7H 8S 8D
3C 7C 9C JC 3D
TS AS 4S 5S 9H
TH AD   

如果你不想要最后一行的迷路空间:

for row in izip_longest(*stacks):
    print ' '.join(col for col in row if col is not None)

这是一种只使用嵌套循环的方法:

longest = max(len(row) for row in stacks)
for i in range(longest):
    for row in stacks:
            if i < len(row):
                    print row[i],
    print

答案 2 :(得分:0)

使用zip转置列表:

for vlist in zip(*stacks):
    print ' '.join(vlist)