简体   繁体   中英

Python: List Index Out of Range / Append List

Here is my list sample (data) : Address list Here is the snippet of the list:

['PO Box 4653, Stockton, California, 95204',
 '157 Adams St., Stockton, California, 95204', ...

Here is my problem : List index out of range (1) 'int' object is not iterable (2)

Please note that solutions like for i in a_list: and for i in range(len(a_list): generates 'Error: list index out of range'

Explanation : My Address list has no nulls and I tried appending empty 'city_list' in a variety of ways as seen on the images... nothing seems to work. I am not sure how can I append my empty list - please help!

Goal : Grab 'a_list' and split each string in a for-in-loop, grab city value (index 1) and append it to an empty list 'city_list'

You may want to just try using a for in loop in the purest sense.

For instance, you can do

arr = [1, 2, 3, 4]

for x in arr:
    print(x)

That should then print out

1
2
3
4

So in your case just use for i in a_list

Just to provide more context to your problem:

Number 1 does not work since you have an element from your list without a ','. Double check your data

Number 2 does not work since you're trying to iterate on an integer, which doesn't make sense. You need to make it a range, ie range(len(a_list))

If you dont care about the indices, just do:

for address in a_list:
    # do something with address

It's simpler, more concise, and more intuitive. Always remember KISS: keep it simple stupid. Usually the simplest solution is the best.

Since you didn't provide us the data, you have to solve # 1 by yourself.

This should work:

a_list = ['PO Box 4653, Stockton, California, 95204','157 Adams St., Stockton, California']

city_list = []
for i in range(0,len(a_list)):
    city_name = a_list[i].split(",")[1].strip()
    city_list.append(city_name)

print(city_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM