在列表中查找小于/大于数字的值

时间:2019-03-02 19:44:09

标签: python python-3.x list integer

我见过类似的话题,但是尝试了他们的方法之后,直到 if 为止,它仍然没有解决。从我在其他主题上阅读的内容来看,这些值不匹配,但是我一直在尝试对其进行修复,并尝试其他方法都没有成功。提前谢谢你的帮助。 这是我的代码:

numbers = []

def calc():

    d=0
    m=0
    single_number=int(input("Enter a number: "))
    number = input("Enter a list of numbers: ")
    numbers = [int(i) for i in number.split()]
    summed =sum(numbers, 0)/len(numbers)
    print("Average: ", summed)
    minimum=min(numbers)
    maximum=max(numbers)
    print("Minimum", minimum)
    print("Maximum", maximum)
    if numbers > single_number:
        d=d+1
    else:
        m=m+1
    print("Amount of numbers in the list that are smaller than the 1st entered number:", m)
    print("Amount of numbers in the list that are bigger than the 1st number:", d)
print(calc())

3 个答案:

答案 0 :(得分:0)

您所缺少的只是一个循环:

for number in numbers: 
    if numbers > single_number:
        d=d+1
    else: # elif numbers < single_number: # what if numbers == single_number?
        m=m+1

您可以做一些改进。 d = d+1是正确的;我更喜欢d += 1

然后(如果您不介意两次遍历列表):

d = sum(1 for number in numbers if number > single_number)
m = sum(1 for number in numbers if number < single_number)

将以紧凑的方式给您dm

答案 1 :(得分:0)

if numbers > single_number正在执行以下操作:

if [1, 2, 3, 4, 5, 6, 7] > 4

那没有任何意义。您是否需要for循环?

for number in numbers:
    if number > single_number:
        d += 1
    elif number < single_number:
        m += 1
    # else doesn't make sense here, since 4 is neither larger _nor_ smaller than 4.

答案 2 :(得分:0)

您可以使用列表推导进行过滤,然后获取结果列表的长度:

d = len([n for n in numbers if n > single_number])
m = len(numbers) - d