【问题标题】:Some trouble when sorting a dictionary排序字典时的一些麻烦
【发布时间】:2015-11-27 15:57:11
【问题描述】:

我在不同的文件夹中有同名的同一个文件。 我想找到最新的修改,所以我使用这个脚本:

import os

from collections import OrderedDict


home = os.path.expanduser('~/')  # path of home, common for al users
result = []
time = {}
name = '.webpyconfig.ini'
for root, dirs, files in os.walk(home):
    dirs[:] = [d for d in dirs if not d == '.Trash']
    if name in files:
        result.append(os.path.join(root, name))

for times in range(0, len(result)):
    time[times] = [result[times], os.stat(result[times]).st_mtime]
    time = OrderedDict(sorted(time.items(), key=lambda x: x[1]))
    maxtime = time[len(time) - 1][1]
    maxpath = time[len(time) - 1][0]


for k in range(0, len(time)):
    print time[k][1], time[k][0]

print ''
print maxtime, maxpath

结果是:

1448636799.0 /Users/Leo/Desktop/Webpy/.webpyconfig.ini
1448637069.0 /Users/Leo/Desktop/Webpy2/.webpyconfig.ini
1448636937.0 /Users/Leo/Documents/Webpy/.webpyconfig.ini

1448636937.0 /Users/Leo/Documents/Webpy/.webpyconfig.ini

如您所见,顺序不正确,因为 Webpy2 是最新创建的文件。 有什么提示吗?

【问题讨论】:

  • 为什么每次迭代都对time有序字典重新排序?

标签: python sorting collections


【解决方案1】:

您将 list 存储为一个值,并按该列表排序:

time[times] = [result[times], os.stat(result[times]).st_mtime]

您的排序键中的x[1] 是整个列表,包含[path, time] 值。这意味着您首先按路径排序,而不是修改时间。

这有点过于复杂了;只需在os.walk() 循环中添加时间,只是时间:

results = {}
for root, dirs, files in os.walk(home):
    dirs[:] = [d for d in dirs if not d == '.Trash']
    if name in files:
        path = os.path.join(root, name)
        results[path] = os.stat(path).m_time

sorted_by_mtime = OrderedDict(sorted(results.items(), key=lambda kv: kv[1]))
for path, time in sorted_by_mtime.items():
    print time, path

【讨论】:

  • 最后一个问题:如何只选择最后一个修改路径?使用“for path, time in sorted...”,我打印了所有的可能性,但我只想要最新的。
  • 那么不要使用排序。您可以将max() 与相同的密钥一起使用,或者如果您发现比目前看到的路径更新的路径(存储一个路径及其mtime 并针对该mtime 测试新路径),则只需在os.walk() 循环中进行测试。
  • 我找到了这个。我删除路径并在 if 循环'code' result[root] = os.stat(root).st_mtime'code' 和 for 循环 path_w = max(result.iterkeys(), key=lambda key 中写入:结果[键])
  • 您可以完全删除.iterkeys() 部分。
  • 当然!但是max() 循环遍历第一个对象,并且直接遍历字典已经为您提供了键。所以max(result, key=result.get) 或者在这里就足够了。 :-)
猜你喜欢
  • 1970-01-01
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多