Python 3.4 - understanding the temp variable in a 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 (like int / float) if USD is displayed in the currency 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]

Here is what I did.

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 actually my question is is there a better way to use a variable inside the list comprehension, so that it looks something like this:

usd_curr = [var = float(elem['currency'].split(',')[0]) for elem in curr if var > 0] 
+4
source share
2 answers

There is no strong syntax for this using understanding. You can use an internal generator to generate values ​​to reduce repetition, but it will become unreadable real, the more difficult it will get.

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

.

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'))
+7

, , :

temp = (float(elem['currency'].split(',')[0]) for elem in curr)  # an iterator, not evaluated yet
usd_curr = [x for x in temp if x > 0]

map filter, , , , , .

0

Source: https://habr.com/ru/post/1629859/


All Articles