【问题标题】:Sorted(items, lambda) with multiple items, one reversedSorted(items, lambda) 有多个项目,一个反转
【发布时间】:2015-05-30 03:05:15
【问题描述】:

我将如何进行以下排序?

import re
list_of_strings=['hulu_delta_20150528.xml', 'hulu_delta_20150524', 
                 'playstation_full_20150529', 'hulu_full_20150528.xml']
sorted(list_of_strings, key=lambda x: (
    x[:3], 
    re.search(r'\d{8}',x).group() if re.search(r'\d{8}',x) else None,
    -x # How would this be done as a third criteria?
))

特别是,我将如何按反向字母顺序作为第三个条件对项目进行排序?最终结果应该是:

['hulu_delta_20150524', 'hulu_full_20150528.xml', 'hulu_delta_20150528.xml', 'playstation_full_20150529']

【问题讨论】:

  • 请发布一个可重现的示例。给我们一个样本列表ftp.nlst(),即使你只是编造一些东西。
  • 排序两次,第二次只使用xreverse=True
  • @AshwiniChaudhary 怎么做?
  • @David542 忽略评论,发布答案。
  • 在您网站的特定示例中 - 为什么您希望 hulu_full 排在第二位?它也不是按字母顺序排列的秒和按日期排列的秒。所以它不是很有说服力你想要做什么 - 除非你有一个大的例子集和解释 - 碰撞。

标签: python string list sorting lambda


【解决方案1】:

您可以比较项目的负序值以按字母顺序反向比较:

#  All hulu strings have same date 
>>> list_of_strings=['hulu_delta_20150528.xml', 'hulu_delta_20150524', 
                     'playstation_full_20150529', 'hulu_full_20150528.xml']
>>> files = sorted(list_of_strings, key=lambda x: (
    x[:3],
    re.search(r'\d{8}',x).group() if re.search(r'\d{8}', x) else None,
    [-ord(c) for c in x]
))
>>> files
['hulu_delta_20150524', 'hulu_full_20150528.xml', 'hulu_delta_20150528.xml', 'playstation_full_20150529']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2018-11-01
    • 2010-11-20
    • 2011-09-02
    相关资源
    最近更新 更多