在python中按整数后缀排序字符串列表

时间:2021-04-04 15:59:08

I have a list of strings:

我有一个字符串列表:

[song_1, song_3, song_15, song_16, song_4, song_8]

I would like to sort them by the # at the end, unfortunately since the lower numbers aren't "08" and are "8", they are treated as larger than 15 in lexicographical order.

我想用最后的#对它们进行排序,遗憾的是,由于较低的数字不是“08”并且是“8”,它们在字典顺序中被视为大于15。

I know I have to pass a key to the sort function, I saw this somewhere on this site to sort decimal numbers that are strings:

我知道我必须将一个键传递给sort函数,我在这个站点的某个地方看到这个字符串的十进制数字:

sorted(the_list, key=lambda a:map(int,a.split('.'))

But that was for "1.2, 2.5, 2.3" but I don't have that case. I thought of replacing '.' with '_' but from what I understand it converts both sides to ints, which will fail since the left side of the _ is a string.

但那是“1.2,2.5,2.3”,但我没有那种情况。我想过要替换'。'使用'_'但根据我的理解,它会将双方转换为整数,这将失败,因为_的左侧是一个字符串。

Any help would be appreciated

任何帮助,将不胜感激

EDIT: I forgot to mention that all the prefixes are the same (song in this example)

编辑:我忘了提到所有前缀都是相同的(本例中的歌曲)

4 个解决方案

#1


12  

You're close.

sorted(the_list, key = lambda x: int(x.split("_")[1]))

should do it. This splits on the underscore, takes the second part (i.e. the one after the first underscore), and converts it to integer to use as a key.

应该这样做。这在下划线上分开,取第二部分(即第一个下划线之后的那个),并将其转换为整数以用作键。

#2


5  

Well, you want to sort by the filename first, then on the int part:

好吧,你想先按文件名排序,然后在int部分排序:

def splitter( fn ):
    try:
        name, num = fn.rsplit('_',1)  # split at the rightmost `_`
        return name, int(num)
    except ValueError: # no _ in there
        return fn, None

sorted(the_list, key=splitter)

#3


3  

sorted(the_list, key = lambda k: int(k.split('_')[1]))

#4


1  

def number_key(name):
   parts = re.findall('[^0-9]+|[0-9]+', name)
   L = []
   for part in parts:
       try:
          L.append(int(part))
       except ValueError:
          L.append(part)
   return L
sorted(your_list, key=number_key)

#1


12  

You're close.

sorted(the_list, key = lambda x: int(x.split("_")[1]))

should do it. This splits on the underscore, takes the second part (i.e. the one after the first underscore), and converts it to integer to use as a key.

应该这样做。这在下划线上分开,取第二部分(即第一个下划线之后的那个),并将其转换为整数以用作键。

#2


5  

Well, you want to sort by the filename first, then on the int part:

好吧,你想先按文件名排序,然后在int部分排序:

def splitter( fn ):
    try:
        name, num = fn.rsplit('_',1)  # split at the rightmost `_`
        return name, int(num)
    except ValueError: # no _ in there
        return fn, None

sorted(the_list, key=splitter)

#3


3  

sorted(the_list, key = lambda k: int(k.split('_')[1]))

#4


1  

def number_key(name):
   parts = re.findall('[^0-9]+|[0-9]+', name)
   L = []
   for part in parts:
       try:
          L.append(int(part))
       except ValueError:
          L.append(part)
   return L
sorted(your_list, key=number_key)