简体   繁体   English

如何确定用户输入python的最大值和最小值之间有多少个数字

[英]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.

相关问题 如何显示用户输入的最大值和最小值? - how to show the max and min from user input? 如何对用户输入的两位或三位数字使用 max() 和 min() - How to use max() and min() for two or three digit numbers from user input 如何使用用户输入的for循环计算最大,最小,平均值? - How to calculate max,min, avg values with for loop taking user input? Python 2.7-尝试查找用户输入的最小和最大数字 - Python 2.7 - Trying to find the min and max of numbers input by the user 如何从python3中的用户输入计算最小值和最大值 - How do I calculate min and max from a user input in python3 如何从Python中的行和列中查找最小值/最大值? - How to find min/max values from rows and columns in Python? 如何在python中找到输入数字的平均值、最小值、最大值和范围? - How to go about finding the average, min, max and the range of the numbers of the input in python? 如何在不使用 Python 列表的情况下找到最大和最小数字?(用户要写数字) - How can I find max and min number without using lists in Python?(user is going to write the numbers) 基本 Python 循环:来自用户输入的最大值和最小值 - Basic Python Loop: Max and Min from User Input 我如何使用用户输入浮点数并在 Python 中找到平均值、最小值、最大值和范围 - How do i use user input floats and find the average, min, max and range in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM