简体   繁体   中英

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

Enter a number (-9999 to end): -3

Enter a number (-9999 to end): -15

Enter a number (-9999 to end): 0

Enter a number (-9999 to end): 10

Enter a number (-9999 to end): 22

Enter a number (-9999 to end): -9999

The list of all numbers entered is:

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

The dictionary with averages is:

{'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. len function give you length of list
I am looping over list if x>=0 it will be positive. if x<0 it will be negative

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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