Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More Pythonic (or perhaps functional) way of creating this list?

I'm returning a list of lists, but the following seems far more convoluted than it should be:

new_list = []
for key, value in group.items(): 
    new_list.extend([['%s%s%s%s%s' % (
    ncode, vendor, extra, value['suffix'], tariff),
    value['latest_cost'], value['rrp'], value['rb']] for tariff in value['trf']])
return new_list
like image 926
urschrei Avatar asked Feb 25 '23 03:02

urschrei


1 Answers

That's not particularly convoluted. You have two "levels", the items in the group which you are expanding into one level. For doing that it's not very convoluted.

A more functional way would be to merge it all into one nested list expression, I think that could be possible. But it sure wouldn't be more readable, and personally I think that's unpythonic (ie, I don't like it).

Personally I would change that list expression to a for loop as well, for readability.

new_list = []
for key, value in group.items(): 
    for tariff in value['trf']:
        name = ''.join(ncode, vendor, extra, value['suffix'], tariff)
        new_list.append(name, value['latest_cost'], value['rrp'], value['rb']])
return new_list

Well, in fact, I would make a generator out of it, because I like them:

def tariffs(group):
    for key, value in group.items(): 
        for tariff in value['trf']:
            name = ''.join(ncode, vendor, extra, value['suffix'], tariff)
            yield [name, value['latest_cost'], value['rrp'], value['rb']]

You might also want to consider making objects out of this. As soon as you have lists of lists or dictionaries of dictionaries it's worth considering making classes instead.

like image 101
Lennart Regebro Avatar answered Mar 17 '23 00:03

Lennart Regebro