我使用我编写的程序合并了两个.txt文件。现在,一旦我将这两个.txt文件合并,我就会得到一个未排序的数据组合。
我的数据看起来像这样
Bud Abbott 51 92.3
Mary Boyd 52 91.4
Hillary Clinton 50 82.1
Don Adams 51 90.4
Jill Carney 53 76.3
Randy Newman 50 41.2
然而我希望它看起来像这样
['Bud', 'Abbott', 51, 92.3]
['Don', 'Adams', 51, 90.4]
['Mary', 'Boyd', 52, 91.4]
['Jill', 'Carney', 53, 76.3]
['Hillary', 'Clinton', 50, 82.1]
['Randy', 'Newman', 50, 41.2]
我如何将我拥有的东西转化为我想要的东西
顺便说一下,我必须得到第一组数据的代码就像这样
def ReadAndMerge():
library1=input("Enter 1st filename to read and merge:")
with open(library1, 'r') as library1names:
library1contents = library1names.read()
library2=input("Enter 2nd filename to read and merge:")
with open(library2, 'r') as library2names:
library2contents = library2names.read()
print(library1contents)
print(library2contents)
combined_contents = library1contents + library2contents # concatenate text
file = combined_contents
lines = []
for l in file:
line = l.strip().split(" ")
lines.append(line)
lines.sort(key=lambda lines: lines[1])
for line in lines:
print(line)
print(combined_contents)
return(combined_contents)
ReadAndMerge()
和库1和库2分别如下所示
Bud Abbott 51 92.3
Mary Boyd 52 91.4
Hillary Clinton 50 82.1
Don Adams 51 90.4
Jill Carney 53 76.3
Randy Newman 50 41.2
如何将其排序并列入清单
我使用您的新行更新了我的程序,但是当我运行它时,我一直收到此错误
Traceback (most recent call last):
File "C:/Users/Shane/Documents/Amer CISC/readandmerge.py", line 30, in <module>
ReadAndMerge()
File "C:/Users/Shane/Documents/Amer CISC/readandmerge.py", line 23, in ReadAndMerge
lines.sort(key=lambda lines: lines[1])
File "C:/Users/Shane/Documents/Amer CISC/readandmerge.py", line 23, in <lambda>
lines.sort(key=lambda lines: lines[1])
IndexError: list index out of range
>>>
答案 0 :(得分:1)
def getListOfLinesInFile(file):
file = open(file, "r")
lines = []
for l in file:
line = l.strip().split(" ")
lines.append(line)
file.close()
return lines
要在您的计划中使用它,只需使用ReadAndMerge
-function with:
def ReadAndMerge():
library1 = input("Enter 1st filename to read and merge: ")
library1_list = getListOfLinesInFile(library1)
library2 = input("Enter 2nd filename to read and merge: ")
library2_list = getListOfLinesInFile(library1)
library_merged = library1_list + library2_list
library_merged.sort(key=lambda library_merged: library_merged[1])
print(*library_merged)
return library_merged