【问题标题】:Python, sort with keyPython,用键排序
【发布时间】:2022-01-14 03:36:42
【问题描述】:

我无法理解 Python 中 sorted 函数中的 key 参数。 假设,给出了以下列表:sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15'],我只想对包含数字的字符串进行排序。

预期输出:['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']

到目前为止,我只能打印带有数字的字符串

def sort_with_key(element_of_list):
    if re.search('\d+', element_of_list):
        print(element_of_list)
    return element_of_list

sorted(sample_list, key = sort_with_key)

但是我如何实际对这些元素进行排序呢? 谢谢!

【问题讨论】:

  • 目前还不清楚你想要实现什么。您作为key 传递的函数适用于每个元素,即您不能使用键仅对某些元素进行排序。但是,您可以对列表的一部分进行排序,并结合未排序(前 3 个元素)和已排序(其余元素)创建新列表。就是说-您如何精确地“排序”日、月和年,即我认为您的意思并不是“排序”,而是按月、日、年排序。另外 - 你是怎么得到这个列表的?
  • @buran 有答案了,谢谢评论!

标签: python list sorting re


【解决方案1】:

我们可以尝试使用 lambda 进行排序:

sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15']
sample_list = sorted(sample_list, key=lambda x: int(re.findall(r'\d+', x)[0]) if re.search(r'\d+', x) else 0)
print(sample_list)

打印出来:

['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']

在 lambda 中使用的逻辑是按每个列表条目中的数字排序,如果条目有一个数字。否则,它会将零值分配给其他条目,将它们放在排序的首位。

【讨论】:

  • 如果天是 02 月是 12 怎么办?我真的不认为 OP 会期望在一个月前一天到来
  • @buran 我只想按数字排序,日/月/年无关紧要。很抱歉造成混乱
  • @buran 我同意这个前提似乎没有意义。但也许给出的样本数据只是轶事,一般问题只是按每个列表条目中的整数值排序。
【解决方案2】:

如果我理解正确,您希望带有数字的字符串以该数字为键进行排序,而没有数字的字符串位于开头?

您需要一个从字符串中提取数字的密钥。我们可以使用str.isdigit() 从字符串中提取数字,使用''.join() 将这些数字重新组合在一起,并使用int() 转换为整数。如果字符串中没有数字,我们将返回 -1,因此它位于所有非负数之前。

sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15', 'answer 42', 'small number 0', 'large number 8676965', 'no number here']

sample_list.sort(key=lambda s: int(''.join(c for c in s if c.isdigit()) or -1))

print(sample_list)
# ['Date ', 'of', 'birth', 'no number here', 'small number 0', 'month 10', 'day 15', 'answer 42', 'year 1990', 'large number 8676965']

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 2020-10-20
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多