python-3.x 列表的排序函数不能正确处理带有数字的字符串

li9yvcax  于 7个月前  发布在  Python
关注(0)|答案(2)|浏览(81)

我为Google python类写了一些代码,它根据元组或字符串中的最后一个元素对列表进行排序,并根据第二个到最后一个元素进行排序。

def better_sort_last(tuples):
    list_1=sorted(tuples, key=len)
    return(sorted(list_1, key=lambda tup:(tup[len(tup)-1],...,[0])))

字符串
这段代码可以很好地处理包含元组的列表:

[(1, 7), (4, 5), (3, 4, 5), (2,)]-> [(2,), (4, 5), (3, 4, 5), (1, 7)]


但对于字符串列表不正确:它没有将['a', 'b', '1a', '2a', '11a', '21a']排序为['a', '1a', '11a', '21a', '2a', 'b'],而是给出['1a', '11a', '2a', '21a', 'a', 'b']
从答案判断,代码似乎读两位数作为一个单一的数字,而不是每个数字是一个单独的元素。我可以做些什么来解决这个问题。
干杯!干杯!

ws51t4hk

ws51t4hk1#

排序实际上工作得很好。在Python中处理字符串排序时,排序是按字符进行的。排序是按字典顺序进行的,这意味着1的Unicode值小于a2也小于a。每个字符的值由它们的ASCII VALUE确定。
如果你仍然想达到你想要的输出,你需要稍微调整一下你的代码。下面是一个例子:

def custom_sort_key(s):
    # Split the string into non-digit prefix and digit suffix parts
    non_digit_prefix = ''.join(filter(str.isalpha, s))
    digit_suffix = ''.join(filter(str.isdigit, s))

    # Convert digit part to integer for proper numeric comparison
    digit_suffix = int(digit_suffix) if digit_suffix else -1  # Use -1 or some flag value for strings without digits

    return non_digit_prefix, digit_suffix

strings = ['a', 'b', '1a', '2a', '11a', '21a']
sorted_strings = sorted(strings, key=custom_sort_key)
print(sorted_strings)

字符串
这样,您首先处理字母,然后才使用isalphaisdigit函数处理数字。

fae0ux8s

fae0ux8s2#

你的lambda在平局的情况下不接受值的所有元素,它只接受第一个元素。要使用所有元素,你可以使用反向值作为键

return sorted(list_1, key=lambda x: x[::-1])

字符串

相关问题