A more Pythonic (or perhaps functional) way to create this list?

I am returning a list of lists, but the following looks a lot more confusing 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 
+4
source share
1 answer

This is not particularly confusing. You have two "levels", elements in a group, which you expand one level. For this, he is not very confused.

A more functional way would be to combine all this into one nested list expression, I think it is possible. But it certainly will not be more readable, and personally I think it is non-pythonic (i.e. I do not like it).

Personally, I would change this list expression to a for loop, as well as 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, actually, 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 may also want to make objects out of this. Once you have lists of lists or dictionaries of dictionaries, you should consider creating classes.

+8
source

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


All Articles