Python, 按键排序
Python, sort with key
我无法理解 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)
但是我实际上如何对这些元素进行排序?
谢谢!
我们可以尝试使用 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 中使用的逻辑是按每个列表条目中的数字排序(如果条目有数字)。否则,它会将零值分配给其他条目,将它们放在排序的第一位。
如果我没理解错的话,你想让有数字的字符串以这个数字为键排序,没有数字的字符串在开头?
您需要一个从字符串中提取数字的键。我们可以使用 str.isdigit()
从字符串中提取数字, ''.join()
将这些数字重新组合在一起,并使用 int()
转换为整数。如果字符串中没有数字,我们将 return -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']
我无法理解 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)
但是我实际上如何对这些元素进行排序? 谢谢!
我们可以尝试使用 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 中使用的逻辑是按每个列表条目中的数字排序(如果条目有数字)。否则,它会将零值分配给其他条目,将它们放在排序的第一位。
如果我没理解错的话,你想让有数字的字符串以这个数字为键排序,没有数字的字符串在开头?
您需要一个从字符串中提取数字的键。我们可以使用 str.isdigit()
从字符串中提取数字, ''.join()
将这些数字重新组合在一起,并使用 int()
转换为整数。如果字符串中没有数字,我们将 return -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']