Reputation: 16085
In my program I need to output a list of points in a grid (tuples of row and column). However, sometimes rows and columns need to be swapped. Currently, I do it like this:
if swapped:
for col, row in points:
print(row, col)
else:
for row, col in points:
print(row, col)
Is there any way I can do it with a single call to print()
?.
Upvotes: 3
Views: 72
Reputation: 26
The easiest and most simple way to do a swap in python is the following:
s1, s2 = s2, s1
In your care the code could look like this
for col, row in points:
if swapped:
col, row = row, col
print(row, col)
Upvotes: 1
Reputation: 20490
This should work as well
points = [(1,2), (3,4)]
swapped = True
for col, row in points:
print((row, col) if swapped else (col, row))
#(2, 1)
#(4, 3)
Another example is
points = [(1,2.5), ('x',4)]
swapped = False
for col, row in points:
print((row, col) if swapped else (col, row))
#(1, 2.5)
#('x', 4)
Upvotes: 0
Reputation: 7896
have a look on below solution, swap the variable:
for col, row in points:
if swapped:
row, col = col, row
print(row, col)
Upvotes: 0
Reputation: 42718
So, swap them:
for col, row in points:
if swapped:
col, row = row, col
print(col, row)
Upvotes: 3
Reputation: 71580
You mean?
for col, row in points:
print(row + ' ' + col if swapped else col + ' ' + row)
Output would be as expected with just using one print
.
Upvotes: 3