创建此列表的更多Pythonic(或者可能是函数式)方式?

发布于 2024-10-17 02:21:15 字数 298 浏览 2 评论 0原文

我正在返回一个列表列表,但以下内容似乎比应有的更加复杂:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尤怨 2024-10-24 02:21:15

这并不是特别复杂。您有两个“级别”,即您要扩展到一个级别的组中的项目。这样做并不是很复杂。

一种更实用的方法是将其全部合并到一个嵌套列表表达式中,我认为这是可能的。但它肯定不会更具可读性,而且我个人认为这是非Pythonic的(即,我不喜欢它)。

就我个人而言,为了可读性,我也会将该列表表达式更改为 for 循环。

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

好吧,事实上,我会用它制作一个生成器,因为我喜欢它们:

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']]

您可能还想考虑用它制作对象。一旦您有了列表列表或词典词典,就值得考虑创建类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文