Home > database >  Rearrange a tuple from a list and print out the new tuples?
Rearrange a tuple from a list and print out the new tuples?

Time:04-11

Sorry if I am asking this question incorrectly.

I created a for loop iterating through this list of tuples. The end result should be to rearrange the tuples from 'year[0]' 'make[1]' 'model[2]' 'color[3]' to 'year[0]' 'color[3]' 'make[1]' 'model[2]'.

My current print out is:

1965 Pontiac GTO blue
1969 Plymouth Roadrunner yellow
2002 Chevrolet Z-28 Camero black

How do grab the last item in each list, and rearrange it to the second position from the list?

car1 = ['1965', 'Pontaic', 'GTO', 'blue']
car2 = ['1969', 'Plymouth', 'Roadrunner', 'yellow']
car3 = ['2002', 'Chevrolet', 'Z-28 Camero', 'black']

allCars = (car1, car2,  car3)

for i in range(len(allCars)):
    print(' '.join(allCars[i]))

CodePudding user response:

You can manually specify the rearrangement that you want by hardcoding the indices, if you know the size of each list in advance:

for car in allCars:
    print(' '.join([car[0], car[3], car[1], car[2]]))

If you need to make it more flexible (i.e. able to handle an arbitrary insertion index, you can use the same approach with list slicing and unpacking):

DEST_IDX = 1

for car in allCars:
    print(' '.join([*car[:DEST_IDX], car[-1], *car[DEST_IDX:-1]]))

Both of these output:

1965 blue Pontaic GTO
1969 yellow Plymouth Roadrunner
2002 black Chevrolet Z-28 Camero

CodePudding user response:

Just use one more tuple to specify the desired order:

car1 = ['1965', 'Pontaic', 'GTO', 'blue']
car2 = ['1969', 'Plymouth', 'Roadrunner', 'yellow']
car3 = ['2002', 'Chevrolet', 'Z-28 Camero', 'black']

cars = (car1, car2,  car3)

order=(0,3,1,2)

for car in cars:
    print(' '.join([car[i] for i in order]))

Prints:

1965 blue Pontaic GTO
1969 yellow Plymouth Roadrunner
2002 black Chevrolet Z-28 Camero
  • Related