我需要從兩個單獨的 txt 檔案中獲取資訊,根據串列的第一個索引(日期)合并和排序它們。我無法同時使用 Lambda 和 DateTime。我目前被困在這個問題上,并且對如何實作這一點沒有任何想法。我也希望得到解釋,以便我理解我在哪里犯了錯誤。
- 我認為我可能正在創建各種串列串列,但是,當我列印上一個串列的 Len 時,它說它包含與預期相同數量的專案。因此,我相信我沒有錯誤地創建具有額外值的串列。
注意:我的編程之旅已經 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
按日期排序的所需輸出 = [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]
uj5u.com熱心網友回復:
由于您的日期格式為 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']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510306.html
