【问题标题】:Sort a list with which values contains (str) numbers or letters对值包含 (str) 数字或字母的列表进行排序
【发布时间】:2021-08-09 14:55:06
【问题描述】:

如何对包含字符串数字和字母的列表进行排序,以先按数字排序,然后按字母排序?

my_list = ["10","2","1","5","a","b","c"]

disable_sorted_list
"1","2","5","10","a","b","c"

【问题讨论】:

标签: python


【解决方案1】:

使用适当的键功能排序:

>>> sorted(my_list, key=lambda s: (not s.isdigit(), int(s) if s.isdigit() else s))
['1', '2', '5', '10', 'a', 'b', 'c']

排序键(not s.isdigit(), int(s) if s.isdigit() else s)是一对(元组)

(bool, str|int)

由于元组是按字典顺序排序的(按元素进行比较,决定第一个不相等的元素),因此数字排在第一位 (False < True)。

我们在排序键中将数字转换为整数,因此它们不会按字母顺序排序

3 < 10  # but 
"10" < "3"

【讨论】:

  • 这太聪明了。我从来没有这样想过,但它是如此的好。
  • @AyushGupta 添加了一些解释
  • @schwobaseggl 非常感谢。这真的很有帮助
【解决方案2】:

这是一个解决方案(未优化但易于理解):

my_list = ["10","2","1","5","a","b","c"]
int_list = [];
str_list = [];
final_list = [];

# separate integers and string in two different arrays
for element in my_list:
  if(element.isdigit()):
    int_list.append(int(element))
  else:
    str_list.append(element)

# sort integers array and strings array
int_list.sort()
str_list.sort()

# cast the integers list into strings list 
int_list = list(map(str, int_list))

# add both list to the final list.
final_list = int_list + str_list

print(final_list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2021-02-22
    • 2022-11-24
    • 2019-02-14
    • 1970-01-01
    • 2012-08-07
    • 2022-11-23
    相关资源
    最近更新 更多