【问题标题】:how do i filter an itertools chain() result?我如何过滤 itertools chain() 结果?
【发布时间】:2010-11-10 21:21:02
【问题描述】:

在我看来, 如果我导入一个 itertools 模块:

from itertools import chain

我用它链接一些对象:

franktags = Frank.objects.order_by('date_added').reverse().filter(topic__exact='art') 
amytags = Amy.objects.order_by('date_added').reverse().filter(topic__exact='art') 
timtags = Tim.objects.order_by('date_added').reverse().filter(topic__exact='art') 
erictags = Eric.objects.order_by('date_added').reverse().filter(topic__exact='art')

ourtags = list(chain(franktags, amytags, timtags, erictags))

然后我如何按“添加日期”订购“我们的标签”?

毫不奇怪,

ourtags = list(chain(franktags, amytags, timtags, erictags)).order_by('date_added')

返回“'list' 对象没有属性 'order_by'”错误。

【问题讨论】:

    标签: python django django-views itertools


    【解决方案1】:
    import operator
    
    ourtags = sorted(ourtags, key=operator.attrgetter('date_added'))
    

    【讨论】:

    • 我认为答案很简单。谢天谢地,我是对的。非常感谢您的帮助。
    • 使用 attrgetter 与使用 lambda 函数有什么不同吗?
    【解决方案2】:

    到代码中的这一点,您已经将所有对象加载到内存和列表中。就像对任何旧的 Python 列表一样对列表进行排序。

    >>> import operator
    >>> ourtags.sort(key=operator.attrgetter('date_added'))
    

    【讨论】:

      猜你喜欢
      • 2013-10-06
      • 2013-02-06
      • 2020-01-31
      • 2019-05-15
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多