所以我有以下代码,它将两个文本文件(字符串)合并到一个列表中。然后这个列表应该提供一个对象。
cat file1.txt
['2.02', '-3.88', '15.25']
['4.40', '-2.36', '14.97']
['5.44', '0.34', '7.34']
['5.76', '0.41', '7.60']
['5.35', '0.19', '13.95']
cat file2.txt
['P1']
['P2']
['P3']
['P4']
['P5']
Code
from ast import literal_eval
#combine both files and return a list
def combiner(infile1, infile2):
with open(infile1) as f1, open(infile2) as f2:
f1_lists = (literal_eval(line) for line in f1)
f2_lists = (literal_eval(line) for line in f2)
for l1, l2 in zip(f1_lists, f2_lists):
l3 = l1 + l2
return l3
class Compass:
def __init__(self, coordx, coordy, coordz, positivity):
self.coordX = coordx
self.coordY = coordy
self.coordZ = coordz
self.posit = posit
def main():
file1 = "file1.txt"
file2 = "file2.txt"
args = combiner(file1, file2)
c = Compass(*args)
print c.coordX + ' ' + c.coordY + ' ' + c.coordZ + ' ' + c.posit
if __name__ == '__main__':
main()
output
2.02 - 3.88 15.25 P1
它当然只输出第一个列表。你会如何继续喂食直到 list 结束? 也许使用 file1.txt 中的行?
最佳答案
第一个问题是您仅从 combiner()
返回列表中的第一行。解决方案是创建一个列表 l3,然后不断向其中追加新行,并在循环结束后返回它。
第二个问题是您有 5 个坐标和正值,因此您还需要 5 个 Compass
实例。解决方案是创建一个实例列表。
解决上述问题,你的代码将如下所示:
from ast import literal_eval
#combine both files and return a list
def combiner(infile1, infile2):
with open(infile1) as f1, open(infile2) as f2:
l3 = [] # this is a list for storing all the lines from both files
f1_lists = (literal_eval(line) for line in f1)
f2_lists = (literal_eval(line) for line in f2)
for l1, l2 in zip(f1_lists, f2_lists):
l3.append(l1 + l2)
return l3 # Return all the lines from both text files
class Compass:
def __init__(self, coordx, coordy, coordz, positivity):
self.coordX = coordx
self.coordY = coordy
self.coordZ = coordz
self.posit = positivity
def main():
file1 = "file1.txt"
file2 = "file2.txt"
args = combiner(file1, file2)
# You have 5 different Compass coordinates, therefore you need 5 different Compass instances
# Therefore make a list of Compass instances
compasslist = [ Compass(args[i][0], args[i][1], args[i][2], args[i][3]) for i in range(len(args))]
# args[i][0] is coordx of i-th line (file1.txt), args[i][1] is coordy of i-th line (file1.txt),
# args[i][2] is coordz of i-th line (file1.txt), and args[i][3] is positivity of i-th line (file2.txt)
# Lets print all the Compass instances
for i in range(len(args)):
print compasslist[i].coordX + ' ' + compasslist[i].coordY + ' ' + compasslist[i].coordZ + ' ' + compasslist[i].posit
if __name__ == '__main__':
main()
关于Python - 用列表提供对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51598154/