我正在尝试排序"时间戳"按月仅。现在代码是:
arr = ["13-16", "5-15", "9-15", "3-14", "12-19", "11-19", "9'19", "5-14"]
arr = sorted(arr, key=lambda str:(str.split("-")[0]))
print(arr)
然而,我在打印时得到的是:
['11-19', '12-19', '13-16', '3-14', '5-15', '5-14', '9-15', '9-19']
有谁知道为什么Python错误地订购了这个?
答案 0 :(得分:2)
您需要将您的月份投放到int
,否则键会按字母顺序排列为字符串。
我还建议你不要扔掉这一年,这样几个月的排序日期就会以明确的顺序解决。
arr = ["13-16", "5-15", "9-15", "3-14", "12-19", "11-19", "9-19", "5-14"]
arr = sorted(arr, key=lambda s: [int(x) for x in s.split("-")])
# ^ cast to an int
print(arr)
输出:
['3-14', '5-14', '5-15', '9-15', '9-19', '11-19', '12-19', '13-16']
答案 1 :(得分:1)
✓ @Goldberg ,输出['3-14', '5-15', '5-14', '9-15', '9-19', '11-19', '12-19', '13-16']
看起来不错,但仍然没有正确的顺序,因为正确的['3-14', '5-14', '5-15', '9-15', '9-19', '11-19', '12-19', '13-16']
你可以使用下面的代码:
基于元组比较的概念:
a = (3, 14)
b = (5, 14)
c = (5, 15)
print (a < b) # True
print (c > b) # True
print (a > c) # False
arr = sorted(arr, key=lambda str:( int(str.split("-")[0]), int(str.split("-")[1])))
print(arr)
# ['3-14', '5-14', '5-15', '9-15', '9-19', '11-19', '12-19', '13-16']
arr = sorted(arr, key=lambda str:( int(str.split("-")[0])))
print(arr)
# ['3-14', '5-15', '5-14', '9-15', '9-19', '11-19', '12-19', '13-16']