修复比较数据并返回行号和数据

我输入了一个程序来比较车辆 A 价格 (v_priceA) 与 carprices.txt 文本文件中的其他各种车辆价格,这些车辆价格位于新行中。


结果应该是一个名为 highprices.txt 的新文本文件,其中所有价格都高于车辆 A 的价格,并在换行符中加上 carprices.txt 中的相关行号


我的问题是能够生成两个文本文件,它们具有更大文件的行号,另一个具有更大的价格,而不是更大的价格本身和行号。我需要解决这个问题。


车辆A价格:2500.50


v_priceA = 2500.50

a_file = 'carprices.txt'

with open(a_file, 'r') as document:

        values = [x for x, value in enumerate(document) if float(value) > v_priceA]


new_file = open('highpriceposition.txt', 'w')

for x in values:

    new_file.write(str(x) + '\n')

new_file.close()




a_file = 'carprices.txt'

with open(a_file, 'r') as document:

    values = [value for value in document if float(value) > v_priceA] 


with open('highprice.txt', 'w') as f:

    for x in values:

        f.write(str(x)+'\n')

位置价格.txt


2 2900.00

3 3500.50

5 25000.30

6 45000.50


梦里花落0921
浏览 129回答 1
1回答

慕少森

当您写入新文件new_file.write()时,您需要将行号和价格都传递给它。IEv_priceA = 2500.50a_file = 'carprices.txt'output_file = 'highprices.txt'with open(a_file, 'r') as document:&nbsp; &nbsp; with open(output_file, 'w') as new_file:&nbsp; &nbsp; &nbsp; &nbsp; for line, price in enumerate(document):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if float(price) > v_priceA:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new_file.write(str(line) + " " + str(price))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # See how I pass both in here?重要的是要知道,每当您open()在 python 中写入文件时,它都会在写入之前"w"擦除该文件中的任何内容。(如果您有兴趣,还有一个附加选项)。 打开的文档。请注意我如何在上面的代码中只打开一次输出文件?那应该有帮助。现在来看看如何enumerate工作。它在 python 中接受一个可迭代对象, 并且对于该可迭代对象中的每个项目返回一个元组,(itemIndex, item)其中至少有一个非常重要的异常,它基本上相当于:def myEnumerate(iterableParameter):&nbsp; &nbsp; i = 0&nbsp; &nbsp; outPutList = []&nbsp; &nbsp; while i < len(iterableParameter):&nbsp; &nbsp; &nbsp; &nbsp; outPutList += (i, iterableParameter[i])&nbsp; &nbsp; return outPutList重要的例外是enumerate创建一个生成器,上面创建一个列表。请参阅进一步阅读。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python