user3125347 - 4 months ago 16
Python Question

How to create a list of strings in python from two "array.flatten()"-ed lists

I'm looking to create the following list in python:

``````list = ["pix420_615", "pix421_615", ... , "pix425_620"]
``````

N.B. Where the list is a list of strings, not values.

From the following two lists:

``````x= [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425,
420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425]

y= [615, 615, 615, 615, 615, 615, 616, 616, 616, 616, 616, 616, 617, 617, 617, 617, 617, 617,
618, 618, 618, 618, 618, 618, 619, 619, 619, 619, 619, 619, 620, 620, 620, 620, 620, 620]
``````

I was wondering how I would go about doing this, and maintain the consistency of corresponding array values...?

This should do the trick. `zip` is the nicest way to do this sort of thing:

``````x = [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425]

y = [615, 615, 615, 615, 615, 615, 616, 616, 616, 616, 616, 616, 617, 617, 617, 617, 617, 617, 618, 618, 618, 618, 618, 618, 619, 619, 619, 619, 619, 619, 620, 620, 620, 620, 620, 620]

z = ['pix{}_{}'.format(a, b) for a, b in zip(x, y)]

print(z)

# Output:
# ['pix420_615', 'pix421_615', 'pix422_615', 'pix423_615', 'pix424_615', 'pix425_615', 'pix420_616', 'pix421_616', 'pix422_616', 'pix423_616', 'pix424_616', 'pix425_616', 'pix420_617', 'pix421_617', 'pix422_617', 'pix423_617', 'pix424_617', 'pix425_617', 'pix420_618', 'pix421_618', 'pix422_618', 'pix423_618', 'pix424_618', 'pix425_618', 'pix420_619', 'pix421_619', 'pix422_619', 'pix423_619', 'pix424_619', 'pix425_619', 'pix420_620', 'pix421_620', 'pix422_620', 'pix423_620', 'pix424_620', 'pix425_620']
``````