【问题标题】:sorting a list of pathnames chronologically in python在python中按时间顺序对路径名列表进行排序
【发布时间】:2017-12-22 09:25:13
【问题描述】:

所以使用各种 os 命令(见下文),我有一个包含 Julian Dates 的路径名列表:

path = '\path\to\directory\with\files\I\want\'
    list_of_pathnames = [os.path.join(dirpath, f) 
        for dirpath, dirnames, files in os.walk(path)
        for f in fnmatch.filter(files, '*specific_string.txt')]

其中路径的文件结构如下:

path = ['\path\to\directory\with\files\I\want\file_2457621_specific_string.txt',
    '\path\to\directory\with\files\I\want\file_2457632_specific_string.txt',
    '\path\to\directory\with\files\I\want\file_2457622_specific_string.txt']

有哪些方法可以按时间顺序从最旧的 (2457621) 到最近的 (2457632) 组织这些朱利安日期?

【问题讨论】:

  • 呃...path.sort()?
  • 你尝试/研究了什么?
  • @StefanPochmann 这将返回 Lexicographical 顺序而不指定 key
  • @Ev.Kounis 那又怎样?在这里等价,不是吗?
  • @StefanPochmann :如果文件名相同,直到每个文件的数字开始,这将起作用。否则对于像 a2b1 这样的东西,它不会。

标签: python list file sorting path


【解决方案1】:

如果你想使用 alphanumeric 顺序而不是 lexicographical,你必须 "get" 从字符串中取出整数并排序基于他们。

一种方法如下:

import os
path = [r'\path\to\directory\with\files\I\want\file_2457621_specific_string.txt',
        r'\path\to\directory\with\files\I\want\file_2457632_specific_string.txt',
        r'\path\to\directory\with\files\I\want\file_2457622_specific_string.txt']

path.sort(key=lambda x: int(os.path.basename(x).split('_')[1]))

仅供参考,如果我的 regex 技能好的话,我会用正则表达式来做。

正如 cmets 所说,在您的示例中,没有区别,但是例如,这两个:

path = [r'\path\file_22_specific_string.txt', r'\path\file_200_specific_string.txt']

会根据数字字符被视为字符串还是数字而产生不同的结果。

【讨论】:

  • 你认为它们有几千年前的年代吗?
  • @StefanPochmann 你永远不知道.. 或者至少我从来不知道。他们似乎确实有一些来自未来'2457622'
  • 嗯?不,那个日期是去年
  • 更准确地说是 2016 年 8 月 21 日。七位数的日期范围从大约 4000 年前到未来 20000 多年。所以我认为假设字典顺序就足够了是非常合理的。
  • 顺便说一句,为什么是“字母数字”而不是“数字”?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多