简体   繁体   中英

Searching and manipulating lists in lists in Python

I have lists of names and cities and am trying to compile a list of the number of users in each city.

I want to have a list that looks like:

citylist = (['New York', 53], ['San Francisco', 23], ['Los Angeles', 54])

etc.

First problem I have is that when I read a new line from the file I need to check whether that city already exists. If it doesn't then I need to add it and give it the number 1. So I have tried:

if city not in citylist:
  citylist.append([city, 1])

Problem with that is that even if the city is already in the list the search doesn't work as I guess it is typing to match the city to the entire element not just the first item of the element. Can someone tell me how to get round that please?

The seocnd part is lets assume that city is found somewhere in citylist, how can I then increment the number next to the city name by 1?

Thanks for any guidance.

Use a dictionary or collections.Counter here. List is not an appropriate data-structure for this task.

Normal dictionary example:

citydict = {'New York': 53,
            'San Francisco': 23,
            'Los Angeles': 54}

Now simply update the dictionary like this:

for line in file_obj:
    city = #do something with line
    citydict[city] = citydict.get(city, 0) + 1

python dict is a proper data structure for what you want to achive. Using defaultdict(int) you can also increment directly for a given city (key of the dict ) even if it is not yet present in the dict .

Use a dictionary to maintain the counters Here is a sample code:

citydict = {}

all_cities = open("cities.txt", "r").readlines()

for city in all_cities:
    if citydict.has_key(city):
        citydict[city] +=1
    else:
        citydict[city] = 1

print citydict.items()

As everyone else said, a dictionay is exactly the datastructure for this type of problems. But if you really want it as list (eg to understand how lists work), you can do it as follows:

def add_to_citylist(citylist, city):
    """modifies citylist according to spec"""

    city_already_in_citylist = False
    #iterate throuch citylists and get city-sub-list as c:
    for c in citylist:
        if c[0] == city:
            #city found, so update count
            c[1] += 1
            #take a note that city was in list:
            city_already_in_citylist = True
    if not city_already_in_citylist:
        #we did not find city in citylist --> add it
        citylist.append([city, 1])


#your citylist should be a list (not a tuple (...) ) since a tuple is unmutable
citylist = [['New York', 53], ['San Francisco', 23], ['Los Angeles', 54]]

add_to_citylist(citylist, "Boston")
add_to_citylist(citylist, "New York")

print citylist

After understanding the idea, you can improve the code by using "return" in the loop which has a similar effect but is more effective since it terminats the loop after the element is found:

def add_to_citylist(citylist, city):
    """modifies citylist according to spec"""

    #iterate throuch citylists and get city-sub-list as c:
    for c in citylist:
        if c[0] == city:
            #city found, so update count
            c[1] += 1
            break
    citylist.append([city, 1])

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