Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

python - Iterate Through Element in List

I have a dataframe containing city names in which I converted to a list. I need to take each indivudal city name and apply search it up using the search_by_city option in US zipcodes to find the corresponding zip. Below is my code

    from uszipcode import SearchEngine
    search =SearchEngine()
    cities= list(data['Nearest City '])
    print(cities)

Output:

 ['Dallas', 'Falls Church', 'Anniston', 'New Brockton']

For example cities[0], gives me the name 'Dallas", and if I apply the following code I get the zipcode of such city.

    zipy= search.by_city(cities[0])  

How do I iterate through the entire list "cities" to get the zip code for each of the city element names within the list? I know itll be a for loop of some kind but having issue

question from:https://stackoverflow.com/questions/65832760/iterate-through-element-in-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this way with list comprehension,

zipy= [search.by_city(city) for city in cities]
print(zipy)

What is does? Iterate each city in the cities list and pass each city to your search.by_city() method and finally you'll get all of the zip of the cities on your zipy as a list of zip codes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...