我試圖從文本文件中獲取信息并將其轉換為列表列表,稍后我將對其進行更多處理。文本文件的格式設置為每條信息由“,”分隔,然后在每個“人”的末尾有一個“\n”例如,111, Joe, Jones, 09-01-1980, 10 -1999年-19日, 95000我很接近。卻被一件小事困住了。我當前的代碼:def readFile(fileName): myFileObj = open(fileName, "r") peopleStr = myFileObj.read() peopleList = peopleStr.split("\n") newPeopleList = [] for el in peopleList: sub = el.split(" ,") newPeopleList.append(sub) print(newPeopleList) return newPeopleList這個 newPeopleList 返回[['111, Joe, Jones, 09-01-1980, 10-19-1999, 95000'], ['113, James, Jo, 10-02-1982, 10-18-1998, 85000'], ['123, Jordan, Joul, 08-04-1988, 10-17-1988, 80000']]但我需要的是[[111, 'Joe', 'Jones', '09-01-1980', '10-19-1999', 95000], [113, 'James', 'Jo', '10-02-1982', '10-18-1998', 85000], [123, 'Jordan', 'Joul', '08-04-1988', '10-17-1988', 80000]]所以他們每個人都可以成為列表中自己的項目!我希望這是有道理的,我感謝任何幫助!
3 回答

烙印99
TA貢獻1829條經驗 獲得超13個贊
listOfLists = []
with open(filename, "r") as msg:
for line in msg:
listOfLists.append(line.strip().replace(" ","").split(","))
msg.close()
這應該可以。您逐行讀取文件,將空格替換為空,用“,”分割每一行以生成一個列表,并將其存儲在列表列表中。

慕桂英546537
TA貢獻1848條經驗 獲得超10個贊
嘗試這個:
newlist = [[y.split(", ")] for x in newPeopleList for y in x] print(newlist)

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
你可以獲得你想要的更多Pythonic:
list(map(lambda x:x.split(', '),open(filename,'r').readlines()))
您自己的代碼中的分隔符“,”是錯誤的,而它需要“,”。
添加回答
舉報
0/150
提交
取消