[英]How to determine how many numbers lie between the max and min values from user input python
for line in file:
line = int(line)
if line <= maximumValue:
counter = counter + 1
if line >= minimumValue:
counter = counter + 1
print (int(line))
file.close()
I am taking a file of a list of numbers, say from 1 to 10. I want to list the max and min values, as well as the values between the min and max. 我正在获取一个数字列表的文件,比如从1到10.我想列出最大值和最小值,以及最小值和最大值之间的值。 When I have my program open the file, it only prints out the total amount of numbers, and doesn't eliminate those that are higher then the max or lower then the min. 当我的程序打开文件时,它只打印出总数量,并且不会消除那些高于最大值或低于最小值的数量。 What am I missing here and what can I do to correct it? 我在这里缺少什么,我该怎么做才能纠正它?
Python supports normal (readable) inequalities: 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)
Also, use with
to open files. 此外,使用with
打开文件。 You don't have to worry about closing them afterwards. 您不必担心事后关闭它们。
An example using a handy property of xrange
: 使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.