Search code examples
pythonarrayslistformattingstring-formatting

Python: pull out elements of given array in certain order


I have an array of arrays with names, addresses, cities, states, and postal codes. Is there a way I can collectively use the elements and display the information in the format of Name, Address, City, State, Postal Code line by line? Also I'm not sure how to get rid of the space at the ends of the array.

This is the array:

[['Alex Morales', ''], ['311 N Sangamon St', ''], ['Chicago, IL 60607', ''],
 ['Delfino Santana', ''], ['1 Main St', ''], ['Belvedere Tiburon, CA 94920', ''],
 ['Ponce De Leon', ''], ['74 King St', ''], ['St. Augustine, FL 32084', ''],
 ['Coit Tower', ''], ['1 Telegraph Hill Blvd', ''], ['San Francisco, CA 94133']]

I am a beginner in Python so no crazy syntax, please!


Solution

  • >>> for name, address, csp in zip(*(iter(i[0] for i in arr),) * 3):
    ...     print(f"Name: {name}  Address: {address}  City/State/Postal: {csp}")
    ...
    Name: Alex Morales  Address: 311 N Sangamon St  City/State/Postal: Chicago, IL 60607
    Name: Delfino Santana  Address: 1 Main St  City/State/Postal: Belvedere Tiburon, CA 94920
    Name: Ponce De Leon  Address: 74 King St  City/State/Postal: St. Augustine, FL 32084
    Name: Coit Tower  Address: 1 Telegraph Hill Blvd  City/State/Postal: San Francisco, CA 94133
    

    The tricky zip stuff is necessary because the data is in a tricky format. It would be better to put this data into (for example) a csv file so that you can group the related information together and avoid the need to zip it after the fact.