Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3.4 list comprehension - calling a temp variable within list

Tags:

python

list

I have a list of dictionaries and I would like to extract certain data based on certain conditions. I would like to extract only the currency (as int/float) if the currency is showing USD and more than 0.

curr = [{'currency': '6000.0000,EUR', 'name': 'Bob'}, 
        {'currency': '0.0000,USD', 'name': 'Sara'}, 
        {'currency': '2500.0000,USD', 'name': 'Kenny'}, 
        {'currency': '0.0000,CND', 'name': 'Debbie'}, 
        {'currency': '2800.0000,USD', 'name': 'Michael'}, 
        {'currency': '1800.0000,CND', 'name': 'Aaron'}, 
        {'currency': '2500.0000,EUR', 'name': 'Peter'}]

Results:

usd_curr = [2500.0000, 2800.0000]

This is what I have done.

usd_curr = [line for line in data if ',USD' in line['currency']]
usd_curr = [float(elem['currency'].split(',')[0]) for elem in curr if float(elem['currency'].split(',')[0]) > 0]

The list works but my question is really this - is there a better way to use a variable inside the list comprehension so it will look something like this:

usd_curr = [var = float(elem['currency'].split(',')[0]) for elem in curr if var > 0] 
like image 453
Cryssie Avatar asked Mar 13 '23 05:03

Cryssie


1 Answers

There's no nice syntax to do that using comprehensions. You could use an inner generator to generate the values to cut the repetition, but it'll get unreadable real quick the more complex it gets.

usd_curr = [
    float(val)
    for val, val_type in (elem['currency'].split(',') for elem in curr)
    if val_type == 'USD' and float(val) > 0
]

I'd suggest using a named generator instead.

def get_currency_by_type(curr, curr_type):
    for elem in curr:
        val, val_type = elem['currency'].split(',')
        if val_type == curr_type and float(val) > 0:
            yield float(val)

usd_curr = list(get_currency_by_type(curr, 'USD'))
like image 72
Jeff Mercado Avatar answered Mar 16 '23 02:03

Jeff Mercado