How to sort this list of strings using a substring?

断了今生、忘了曾经 提交于 2020-01-25 08:31:06

问题


I have a list whose elements are like the following:

Region_1.csv, Region_33.csv, Region_2.csv, Region_4.csv, Region_105.csv, ....

The list has all numbers ranging from 1-105 with none missing. I want to sort this list according to the region number such that it looks like this:

Region_1.csv, Region_2.csv, Region_3.csv, Region_4.csv, Region_105.csv etc.

Since the numbers have variable digits, I am struggling to sort this list.

Thanks.


回答1:


You can use sorted with a custom function, splitting first by . and then by _:

res = sorted(L, key=lambda x: int(x.split('.')[0].split('_')[-1]))

print(res)

['Region_1.csv', 'Region_2.csv', 'Region_4.csv', 'Region_33.csv', 'Region_105.csv']



回答2:


lst.sort(key=lambda x: int(x.split('_')[1].split('.')[0]))
print(lst)

# ['Region_1.csv', 'Region_2.csv', 'Region_4.csv', 'Region_33.csv', 'Region_105.csv']



回答3:


Using re module, if you want to find in string something fancy:

l = ['Region_105.csv', 'Region_1.csv', 'Region_33.csv', 'Region_2.csv', 'Region_4.csv']

import re
print(sorted(l, key=lambda v: int(re.findall('\d+', v)[0])))

Output:

['Region_1.csv', 'Region_2.csv', 'Region_4.csv', 'Region_33.csv', 'Region_105.csv']




回答4:


You can also use the find method of strings:

inList = ['Region_1.csv', 'Region_33.csv', 'Region_2.csv', 'Region_4.csv', 'Region_105.csv']

outList = sorted(inList, key=lambda elem: int(elem[elem.find('_')+1:elem.find('.')]))

print(outList)

Output:

['Region_1.csv', 'Region_2.csv', 'Region_4.csv', 'Region_33.csv', 'Region_105.csv']



回答5:


You could also try this:

>>> l = ['Region_105.csv', 'Region_1.csv', 'Region_33.csv', 'Region_2.csv', 'Region_4.csv']
>>> sorted(l, key=lambda x: int(''.join(filter(str.isdigit, x))))
['Region_1.csv', 'Region_2.csv', 'Region_4.csv', 'Region_33.csv', 'Region_105.csv']



回答6:


You can extract the region number using regular expressions and create a dictionary of the form {region number: fileName} and then sort the dictionary based on the keys. Code for extracting region number and create dictionary:

import re
files=['Region_1.csv','Region_33.csv','Region_2.csv','Region_4.csv','Region_105.csv']
d=dict()
for f in files:
   rnum=re.find('[a-bA-B]_([0-9])\.csv$',f)
   d[rnum]=f

For sorting the items in dictionary, refer : How can I sort a dictionary by key?



来源:https://stackoverflow.com/questions/51301769/how-to-sort-this-list-of-strings-using-a-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!