0
 for line in file:
    line = int(line)
    if line <= maximumValue:
        counter = counter + 1
    if line >= minimumValue:
        counter = counter + 1
    print (int(line))
file.close()

我正在获取一个数字列表的文件,比如从 1 到 10。我想列出最大值和最小值,以及最小值和最大值之间的值。当我让我的程序打开文件时,它只打印出数字的总数,并不会消除那些高于最大值或低于最小值的数字。我在这里遗漏了什么,我能做些什么来纠正它?

4

2 回答 2

2

Python 支持正常(可读)不等式:

numbers = []
counter = 0

with open('filename.txt', 'r') as handle:
    for line in handle:
        number = int(line)

        if minimumValue <= number <= maximumValue:
            numbers.append(number)
            counter += 1

print(counter)
print(numbers)

此外,用于with打开文件。您不必担心事后关闭它们。

于 2012-11-02T02:01:19.870 回答
0

使用方便属性的示例xrange

MIN = 3
MAX = 7

valid_range = xrange(MIN, MAX+1)
with open('file') as fin:
    nums = (int(line) for line in fin)
    valid_vals = [num for num in nums if num in valid_range]
    # or if you just want count of valid values
    count = sum(1 for num in nums if num in valid_range)

print valid_vals, len(valid_vals)
于 2012-11-02T02:07:15.783 回答