Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中按子字符串对目录排序_Python - Fatal编程技术网

python中按子字符串对目录排序

python中按子字符串对目录排序,python,Python,假设:我有目录名:dir1 Dir1/ 我想按yxxx和WXX排序,并按顺序打印: A_Y2016W20 A_Y2016W25 A_Y2017W15 A_Y2017W30 B_Y2017W30 B_Y2017W35 如何使用排序?您可以通过以下方式进行操作- a = ['A_Y2016W25', 'A_Y2017W15', 'B_Y2017W30', 'A_Y2016W20', 'B_Y2017W35', 'A_Y2017W30'] def ext(strng): return o

假设:我有目录名:dir1 Dir1/

我想按yxxx和WXX排序,并按顺序打印:

A_Y2016W20
A_Y2016W25
A_Y2017W15
A_Y2017W30

B_Y2017W30
B_Y2017W35
如何使用排序?

您可以通过以下方式进行操作-

a = ['A_Y2016W25', 'A_Y2017W15', 'B_Y2017W30', 'A_Y2016W20', 'B_Y2017W35', 'A_Y2017W30']

def ext(strng):
    return ord(strng[0]), int(strng[3:7]), int(strng[8:])

a.sort(key = ext) #['A_Y2016W20', 'A_Y2016W25', 'A_Y2017W15', 'A_Y2017W30', 'B_Y2017W30', 'B_Y2017W35']
我会做好的


事实上,您不需要执行任何类型的子字符串,因为您在要执行的排序中已经具有从左到右的优先级。

另一种方法是使用
sort()
和基于regex键的函数,例如:

import re 

def sort_regex(regex, a):
    data = re.search(regex, a)
    return data.group(0) if data else ''

a = ['A_Y2016W25', 'A_Y2017W15', 'B_Y2017W30', 'A_Y2016W20', 'B_Y2017W35', 'A_Y2017W30']

a.sort(key=lambda x: sort_regex(r'Y\d{4}', x))
print(a)

a.sort(key=lambda x: sort_regex(r'W\d{2}', x))
print(a)

a.sort(key=lambda x: sort_regex(r'Y\d{4}W\d{2}', x))
print(a)
输出:

['A_Y2016W25', 'A_Y2016W20', 'A_Y2017W15', 'B_Y2017W30', 'B_Y2017W35', 'A_Y2017W30']
['A_Y2017W15', 'A_Y2016W20', 'A_Y2016W25', 'B_Y2017W30', 'A_Y2017W30', 'B_Y2017W35']
['A_Y2016W20', 'A_Y2016W25', 'A_Y2017W15', 'B_Y2017W30', 'A_Y2017W30', 'B_Y2017W35']

你试过什么?请尝试先编写代码,并发布一些示例以获得更多帮助。这是过度设计的,一个基本的sort()将在其上下文中解决OP的问题。
import re 

def sort_regex(regex, a):
    data = re.search(regex, a)
    return data.group(0) if data else ''

a = ['A_Y2016W25', 'A_Y2017W15', 'B_Y2017W30', 'A_Y2016W20', 'B_Y2017W35', 'A_Y2017W30']

a.sort(key=lambda x: sort_regex(r'Y\d{4}', x))
print(a)

a.sort(key=lambda x: sort_regex(r'W\d{2}', x))
print(a)

a.sort(key=lambda x: sort_regex(r'Y\d{4}W\d{2}', x))
print(a)
['A_Y2016W25', 'A_Y2016W20', 'A_Y2017W15', 'B_Y2017W30', 'B_Y2017W35', 'A_Y2017W30']
['A_Y2017W15', 'A_Y2016W20', 'A_Y2016W25', 'B_Y2017W30', 'A_Y2017W30', 'B_Y2017W35']
['A_Y2016W20', 'A_Y2016W25', 'A_Y2017W15', 'B_Y2017W30', 'A_Y2017W30', 'B_Y2017W35']