Marty
Marty

Reputation: 85

How do you take data from a tuple only if it contains a particular element?

Specifically, I have some functions that take population data from particular states in the US from a .csv file. The state code is the first [0] element in the list, so AK, or MS, MT, etc. It is saved as a tuple with things like (state,county, population, etc.) and added to a list; data_list[].

I then prompt for an input of either a particular state, or the option to look at all of the data by inputing "all." How do I go through each tuple and only append the desired states?

Here's what I have so far (note that I do have other functions before this, as well as a main() but they all seem to work fine at this point:

STATES={'AK','AL','etc.','etc.'}
state = input("\nEnter state code or 'all' or 'quit': ")
def extract_data(data_list,state):
    state_list=[]
    for tup in data_list:
        if state=="all":
            state_list= data_list
        if state in STATES: 
            if tup[0]==state:
                state_list.append(tup)
    print(state_list)

If there's any clarification needed from other functions, I can provide it, but for now, the function just returns all of the data, not just the desired state.

Upvotes: 0

Views: 72

Answers (2)

Patrick Haugh
Patrick Haugh

Reputation: 60994

You can do this a good deal more cleanly using a list comprehension

def extract_data(data_list, state='all'):
    if state == 'all':
        return data_list
    return [t for t in data_list if t[0] == state]

Upvotes: 3

Marty
Marty

Reputation: 85

I may have figured it out already, but would love some input. Here's what I changed:

STATES={'AK','AL','etc.','etc.'}
state = input("\nEnter state code or 'all' or 'quit': ")
def extract_data(data_list,state):
    state_list=[]
    tup_data=[]
    for tup in data_list:
        if state=="all":
            state_list= data_list
        if state in STATES: 
            if tup[0]==state:
                tup_data=tup
                state_list.append(tup_data)
    print(state_list)

That just printed off data for a particular state, so I believe that's all I need. However, I'd love any feedback for improvements or anything like that.

Upvotes: 0

Related Questions