创建此列表的更多Pythonic(或者可能是函数式)方式?
我正在返回一个列表列表,但以下内容似乎比应有的更加复杂:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这并不是特别复杂。您有两个“级别”,即您要扩展到一个级别的组中的项目。这样做并不是很复杂。
一种更实用的方法是将其全部合并到一个嵌套列表表达式中,我认为这是可能的。但它肯定不会更具可读性,而且我个人认为这是非Pythonic的(即,我不喜欢它)。
就我个人而言,为了可读性,我也会将该列表表达式更改为 for 循环。
好吧,事实上,我会用它制作一个生成器,因为我喜欢它们:
您可能还想考虑用它制作对象。一旦您有了列表列表或词典词典,就值得考虑创建类。
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.
Well, in fact, I would make a generator out of it, because I like them:
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.