0

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!

2
  • Why is this split up like this in the first place? Commented Jun 30, 2020 at 21:16
  • I created a file with information and am reading from the file by collecting all the lines from that file and placing them into this array. Commented Jun 30, 2020 at 21:17

2 Answers 2

1

Create a list of dictionaries by iterating over the list in strides of 3:

l = [['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']]

info = [{"name": l[i][0], "street": l[i+1][0], "city": l[i+2][0]}
        for i in range(0, len(l), 3)]

Now you have all the related information in each dictionary, and you can print it out:

for x in info:
    print(f"Name: {x['name']}\nAddress: {x['street']} x['city']}\n")
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I wanted to do, thanks! I must add that I keep getting a syntax error when plugging this into my IDE. I can't seem to figure out why.
I had a typo: , after "street" instead of :
0
>>> 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.