我目前有一段代码可以分为两部分。第一个段从本地驱动器上的特定路径打开现有文本文件,然后根据某些索引将其排列到子列表列表中。在第二个段中,我采用我创建的子列表并将它们分组在类似的索引上以简化它们(从def merge_subs开始)。我没有得到错误代码,但是当我尝试打印变量答案时,我没有收到结果。我没有正确循环原始的子列表列表吗?最后,我希望有一个包含这些循环的最终产品的变量,以便我可以将其内容写入新的文本文件。这是我正在使用的代码:
from itertools import groupby, chain
from operator import itemgetter
with open ("somepathname") as g:
# reads text from lines and turns them into a list sub-lists
lines = g.readlines()
for line in lines:
matrix = line.split()
JD = matrix [2]
minTime= matrix [5]
maxTime= matrix [7]
newLists = [JD,minTime,maxTime]
L = newLists
def merge_subs(L):
dates = {}
for sub in L:
date = sub[0]
if date not in dates:
dates[date] = []
dates[date].extend(sub[1:])
answer = []
for date in sorted(dates):
answer.append([date] + dates[date])
def openfile(self):
filename = askopenfilename(parent=root)
self.lines = open(filename)
def simplify(self):
g = self.lines.readlines()
for line in g:
matrix = line.split()
JD = matrix[2]
minTime = matrix[5]
maxTime = matrix[7]
self.newLists = [JD, minTime, maxTime]
print(self.newLists)
dates = {}
for sub in self.newLists:
date = sub[0]
if date not in dates:
dates[date] = []
dates[date].extend(sub[1:])
answer = []
for date in sorted(dates):
print(answer.append([date] + dates[date]))
enter code here
在这里输入代码