DwightD
DwightD

Reputation: 157

Python 3-x: Nested list in a for loop - how to get a "horizontal" output

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")

How do I make it so that the output becomes:

TS  6S  JS
AH  5S  AS

Instead of:

TS
AH

6S
5S

JS
AS

I posted a question similar to this but I wasn't being specific enough, and I edited too late. Apologies in advance

EDIT - 'cards' code:

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

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

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

    return hands

Upvotes: 3

Views: 776

Answers (3)

Andrew of Scappoose
Andrew of Scappoose

Reputation: 467

Simple, run the loop twice. Character output only allows you to operate on one line at a time, reliably. To print in vertical columns requires stripping the data in two passes. Using an IF statement, inside a loop slows down processing compared to just running it twice. Python can optimize this kind of code, because it doesn't need branch prediction.

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()

Upvotes: 0

Matthias Fripp
Matthias Fripp

Reputation: 18625

You could get a little fancy and use zip(*) to transpose cards. Then printing is simple, like this:

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

output:

TS  6S  JS
AH  5S  AS

Upvotes: 4

Pyd
Pyd

Reputation: 6159

I think you need,

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")

Upvotes: 0

Related Questions