python排序日期而不使用內置函式sort(),但我想要的是
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-11-16',
'2010-11-22', '2010-11-23', '2010-11-26', '2010-12-02', '2010-12-13',
'2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']
我確實閱讀了類似的問題并嘗試解決它,但仍然存貨

(圖片)代碼和輸出第二個版本:

(第三版)嘗試只使用“input_list”,如果那樣洗掉“new_list”以節省記憶體,我該怎么做?
import datetime
def date_sorting_operation(input_list):
new_list = []
dates = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in input_list]
while input_list:
min = input_list[0]
for x in input_list:
if x < min:
min = x
new_list.append(min)
input_list.remove(min)
return new_list
customer_date_list = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
print (date_sorting_operation(customer_date_list))
(圖片)嘗試只使用“input_list”,洗掉“new_list”以節省記憶體:

uj5u.com熱心網友回復:
實際上,您的文本日期串列幾乎采用 ISO 可排序格式,只是偶爾月份可能是一位而不是兩位。如果我們用零填充月份,排序應該起作用:
customer_date_list = ['2011-06-02', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
output = [re.sub(r'-(\d)-', r'-0\1-', x) for x in customer_date_list]
output.sort()
print(output)
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-12-02',
'2010-12-13', '2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']
uj5u.com熱心網友回復:
嘗試這個
import datetime
customer_date_list = ['2011-06-02', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
lst = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in customer_date_list]
outLst = []
for _ in customer_date_list:
m = min(lst)
lst.remove(m)
outLst.append(m.strftime('%Y-%m-%d'))
print(outLst)
輸出
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-12-02',
'2010-12-13', '2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']
AS OP 說“我可以只使用一個沒有 outLst 的串列 lst 來保存在同一個串列中。(為了節省記憶體)”
import datetime
customer_date_list = ['2011-06-02', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30']
lst = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in customer_date_list]
for i in range(len(customer_date_list)):
m = max(lst[i:])
lst.remove(m)
lst.insert(0,m.strftime('%Y-%m-%d'))
print(lst)
輸出
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-12-02',
'2010-12-13', '2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510497.html
標籤:Python排序
下一篇:C插入排序不是從最小到最大排序
