[英]how to merge and sort a list with datetime and lambda in Python3?
我需要從兩個單獨的 txt 文件中獲取信息,根據列表的第一個索引(日期)合並和排序它們。 我在同時使用 Lambda 和 DateTime 時遇到問題。 我目前被困在這個問題上,並且對如何實現這一點沒有任何想法。 我也希望得到解釋,以便我理解我在哪里犯了錯誤。
注意:我的編程之旅已經 2 個月了,並且已經搜索了不同的方法來解決我的問題,但我仍然不夠努力。 我昨天在一個更簡單的問題上實現了相同的概念,其中第一個索引是個位數的 INT,這要容易得多。 由於 Date 是第一個索引,我無法在我的代碼中同時理解 DateTime 和 lambda 的語法。 我感謝所有的幫助和意見!
from datetime import datetime
from typing import Any, List
def get_list1(file_name: str) -> Any:
list1 = []
with open(file_name, newline='') as inputFile:
lines = inputFile.readlines()
for line in lines:
line = line.replace("\r\n", '')
seperate = line.split(";")
list1.append(seperate)
return list1
def get_list2(file_name: str) -> Any:
list2 = []
with open(file_name, newline='') as inputFile:
lines = inputFile.readlines()
for line in lines:
line = line.replace("\r\n", '')
seperate = line.split(";")
list2.append(seperate)
return list2
def mergeLists(list1:List, list2:List):
newList = []
for item in list1:
newList.append(list1)
for item in list2:
newList.append(list2)
print(len(newList))
return(newList)
def sortedList(newList:List):
orderedList = sorted(newList, key=lambda x: datetime.datetime.strptime(x[0]))
print(orderedList)
list1 = get_list1("bitcoin.txt")
list2 = get_list2("exchange.txt")
newList =mergeLists(list1, list2)
sortedList(newList)
bitcoin.txt =
2022-08-01;buy;100
2022-08-04;buy;50
2022-08-06;buy;10
exchange.txt =
2022-08-02;buy;200
2022-08-03;sell;300
2022-08-05;sell;25
所需 output 按日期排序 = [2022-08-01;buy;100, 2022-08-02;buy;200, 2022-08-03;sell;300, 2022-08-04;buy;50, 2022-08 -05;賣出;25, 2022-08-06;買入;10]
由於您的日期格式為 yyyy-mm-dd(可按字符串排序)和每行的第一個文本,因此您可以對它們進行排序,而無需將它們轉換為日期時間。 這應該這樣做:
def file_to_list(file: str) -> list:
out = []
with open(file) as f:
for line in f:
out.append(line.strip())
return out
bitcoin = file_to_list("bitcoin.txt")
exchange = file_to_list("exchange.txt")
combined = bitcoin + exchange
sorted(combined)
出去:
['2022-08-01;buy;100',
'2022-08-02;buy;200',
'2022-08-03;sell;300',
'2022-08-04;buy;50',
'2022-08-05;sell;25',
'2022-08-06;buy;10']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.