简体   繁体   English

在 Python 中对列表进行计数、相加和求平均值

[英]Counting, adding and averaging from a list in Python

Ten numbers are to be read in from the keyboard.十个数字将从键盘读入。 After this write how many of these numbers were positive, the total of these positive numbers, and the mean (average) of the positive numbers.在此之后写下这些数字中有多少是正数,这些正数的总和以及正数的平均值(平均值)。

This is what I have so far这是我到目前为止

print ("Input 10 numbers, separated by commas")

k=[x for x in input("Enter number:").split(',')]

for l in k:
    print (l)
    if l > 0:
        print("positive")
    else:
        print("negative")

However I have no idea where to go and any help would be much appreciated!但是我不知道该去哪里,任何帮助将不胜感激!

You can define two variables positive_total and positive_count to keep track, while going through the list您可以定义两个变量positive_totalpositive_count来跟踪,同时浏览列表

print ("Input 10 numbers, separated by commas")

k=[x for x in input("Enter number:").split(',')]

positive_total = 0 #total of all positive integers
positive_count = 0 #keeps count of number of positive integers
for l in k:
    print (l)
    if l > 0:
        positive_total += l
        positive_count += 1
        print("positive")
    else:
        print("negative")

print('Count of positive integers = {}'.format(positive_count))
print('Total of positive integers = {}'.format(positive_total))
print('Average of positive integers = {}'.format(positive_total/positive_count))

This should be an adequate solution:这应该是一个适当的解决方案:

num_list = []

for i in range(10):
    num = input("Enter number:")
    num_list.append(int(num))

positives = 0
pos_nums = []

for num in num_list:
    if num > 0:
        positives += 1
        pos_nums.append(num)

pos_sum = sum(pos_nums)

print(positives)
print(pos_sum)
print(pos_sum/positives)

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

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