简体   繁体   English

从多个输入创建列表并平均输出

[英]creating a list from multiple inputs and averaging the outputs

I am trying to write a code to perform the following I was hoping someone could point me in the right direction and explain/ show me what I need to do. 我试图编写代码来执行以下操作,希望有人可以指出正确的方向并向我解释/告诉我需要做什么。 thanks! 谢谢!

Sample: 样品:

Enter a number (-9999 to end): 4 输入数字(以-9999结尾):4

Enter a number (-9999 to end): -3 输入数字(以-9999结尾):-3

Enter a number (-9999 to end): -15 输入数字(以-9999结尾):-15

Enter a number (-9999 to end): 0 输入数字(以-9999结尾):0

Enter a number (-9999 to end): 10 输入数字(以-9999结尾):10

Enter a number (-9999 to end): 22 输入数字(以-9999结尾):22

Enter a number (-9999 to end): -9999 输入数字(以-9999结尾):-9999

The list of all numbers entered is: 输入的所有数字的列表为:

[4, -3, -15, 0, 10, 22] [4,-3,-15,0,10,22]

The dictionary with averages is: 带有平均值的字典是:

{'AvgPositive': 12.0, 'AvgNonPos': -6.0, 'AvgAllNum': 3.0} {'AvgPositive':12.0,'AvgNonPos':-6.0,'AvgAllNum':3.0}

To create your list of integers from input, do something like this: 要根据输入创建整数列表,请执行以下操作:

myList = []
while True:
    myInput = raw_input('Please enter a number: ')
    if myInput == '-9999':
        break
    else:
      myList.append(int(myInput.strip()))

then do what you need to do with that list of integers. 然后执行该整数列表所需的操作。

you can try like this: 您可以这样尝试:

my_num = []
while True:
    n = input("Enter a number (-9999 to end):")
    if n == '-9999':
        break               # if user enters -9999 it will come out of loop
    my_num.append(int(n))
avg = sum(my_num)/len(my_num)
avg_pos = sum([ x for x in my_num if x>=0 ])/len(my_num)
avg_neg = sum([ x for x in my_num if x<0 ])/len(my_num)

now you can put this all in dictionary easily 现在您可以轻松地将所有内容放入字典中

sum function give you sum of list. sum函数为您提供列表的总和。 len function give you length of list len函数为您提供列表长度
I am looping over list if x>=0 it will be positive. 我正在遍历列表,如果x> = 0它将是正数。 if x<0 it will be negative 如果x <0将为负

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM