我有这样的字典:
paths = {19: 'routes/web.php', 44: 'app/Http/Controllers/SearchController.php', 27: 'app/Filters/Filters.php', 32: 'resources/views/layouts/app.blade.php', 21: 'composer.json', 39: '.env'}
prepared = [(key, value) for key, value in paths.items()]
我想按顺序对它们进行排序,以便如果字典的值包含3个或更多的正斜杠,则应首先按最长的长度对其进行排序,然后再按不包含这些值的值(字符串)进行排序任何正斜杠,最后包含2或1个斜杠的值(字符串),按长度排序,最短的为最短。输出应如下所示:
prepared >>>
[(44, 'app/Http/Controllers/SearchController.php'), (32, 'resources/views/layouts/app.blade.php'), (39, '.env'), (21, 'composer.json'), (19, 'routes/web.php'), (27, 'app/Filters/Filters.php')]
任何解决方案都会有所帮助。
答案 0 :(得分:2)
您可以将sorted
与自定义键功能一起使用,该功能会产生tuple
。您尚未指定领带会发生什么,因此您所需的输出不匹配,并且在一般情况下没有唯一的解决方案。
def sorter(x):
n = x[1].count('/')
i = -n if n >= 3 else 0
j = 0 if n == 0 else 1
k = n
return i, j, k
prepared = sorted(paths.items(), key=sorter)
[(32, 'resources/views/layouts/app.blade.php'),
(44, 'app/Http/Controllers/SearchController.php'),
(21, 'composer.json'),
(39, '.env'),
(19, 'routes/web.php'),
(27, 'app/Filters/Filters.php')]