python3x:for循环中的嵌套列表如何获得“水平”输出

2024-04-24 12:48:08 发布

您现在位置:Python中文网/ 问答频道 /正文

for i, j in cards: 
# cards = a list containing list of cards - RANDOM OUTPUTS, more pairs can be added to the list depending on the number that the user puts in
        print(i)
        print(j)
        print("\t")

如何使输出变为:

TS  6S  JS
AH  5S  AS

而不是:

TS
AH

6S
5S

JS
AS

我发布了一个类似的问题,但我不够具体,我编辑太晚了。提前道歉

编辑-“卡”代码:

deck = deck_create()
def deal_cards(deck, num_players):

    cards= []
    for i in range(num_players):

        hands.append([deck.pop(), deck.pop()])

    return hands

Tags: thein编辑forasjsnumlist
3条回答

简单,运行循环两次。字符输出只允许您一次对一行进行可靠的操作。要在垂直列中打印,需要分两次剥离数据。与只运行两次循环相比,在循环内使用IF语句会减慢处理速度。Python可以优化这类代码,因为它不需要分支预测。你知道吗

cards=[ ("TS","AH"), ("6S","5S"),("JS","AS") ] #This is dummy data, to match your code. Replace it.
for i,j in cards: 
    print (i,"\t", end="")
print()
for i,j in cards:
    print (j,"\t", end="")
print()

我想你需要

for i in range(len(cards[0])):
    for items in cards:
        if items[i] in cards[-1]:
            print(items[i],end="\n")
        else:
             print(items[i],end="\t")

你可以用zip(*)来转置cards。打印很简单,如下所示:

cards=[("TS", "AH"), ("6S", "5S"), ("JS", "AS")]
for round in zip(*cards):
    print('\t'.join(round))

输出:

TS  6S  JS
AH  5S  AS

相关问题 更多 >