Home > Back-end >  How to Get python print result in one line for 2d array
How to Get python print result in one line for 2d array

Time:08-03

class Passenger:

def __init__(self, name, IsBooked):
    self.name = name
    self.IsBooked = IsBooked

Seats = [[0]*2]*2

for i in range(2):

for j in range(2):
    Seats[i][j] = Passenger('', False)

for i in range(2):

for j in range(2):
    if(Seats[i][j].IsBooked == False):
        print('X')
print('\n')

I want to print the output as

X X

X X

But I am getting the result as

I am getting the result as

Where Should I modify the code to get the expected result?

CodePudding user response:

class Passenger:
    def __init__(self, name, IsBooked):
        self.name = name
        self.IsBooked = IsBooked


Seats = [[0]*2]*2
for i in range(2):
    for j in range(2):
        Seats[i][j] = Passenger('', False)

for i in range(2):
    for j in range(2):
        if(Seats[i][j].IsBooked == False):
            print('X')

You will need to remove print('\n') in last line as it is being executed after every two elements.

CodePudding user response:

OK

class Passenger:
    def __init__(self, name, IsBooked):
        self.name = name
        self.IsBooked = IsBooked


txt = ''
Seats = [[0]*2]*2
for i in range(2):
    for j in range(2):
        Seats[i][j] = Passenger('', False)

for i in range(2):
    for j in range(2):
        if(Seats[i][j].IsBooked == False):
            txt  = 'X '
            txt_with_new_line  = 'X\n'

    print(txt   '\n')
    txt = ''
#   Result
#   X X
#
#   X X
  • Related