固定比较数据和返回行号和d

2024-03-29 10:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经输入了一个程序来比较a车的价格(vïpriceA)与a车的各种其他车辆价格carprices.txt文件位于新行中的文本文件。你知道吗

结果应该是一个名为高价.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

Tags: 文件intxtforvalueaswith价格
1条回答
网友
1楼 · 发布于 2024-03-29 10:25:54

当您写入新文件new_file.write()时,您需要同时传递行号和价格。即

v_priceA = 2500.50
a_file = 'carprices.txt'
output_file = 'highprices.txt'


with open(a_file, 'r') as document:
    with open(output_file, 'w') as new_file:
        for line, price in enumerate(document):
            if float(price) > v_priceA:
                new_file.write(str(line) + " " + str(price))
                # See how I pass both in here?

重要的是要知道,每当你在python中把一个文件open()写成write "w"的时候,它都会在写入文件之前清除该文件中的所有内容。(如果您感兴趣,可以使用附加选项)。 Docs for Open。你知道吗

注意我如何在上面的代码中只打开一次输出文件?这应该有帮助。你知道吗

现在来看看enumerate是如何工作的。它需要一个iterable object in python 对于iterable中的每个项,返回一个(itemIndex, item)元组,其中至少有一个非常重要的异常,它基本上是简洁的等价物:

def myEnumerate(iterableParameter):
    i = 0
    outPutList = []
    while i < len(iterableParameter):
        outPutList += (i, iterableParameter[i])
    return outPutList

重要的例外是enumerate创建了一个生成器,其中如上所述创建了一个列表。见further reading。你知道吗

相关问题 更多 >