简体   繁体   English

在 python 中查找随机列表的浮点平均值

[英]Finding float average of random list in python

I have looked on several websites, books, and in the documentation and I can't figure out what I am doing wrong.我查看了几个网站、书籍和文档,但我无法弄清楚我做错了什么。 I try to ask for help as a last resort, so that I can learn on my own, but I have spent far too long trying to figure this out, and I am sure it is something really simple that I am doing wrong, but I am learning.我尝试寻求帮助作为最后的手段,以便我可以自学,但我花了太长时间试图弄清楚这一点,我确信我做错了很简单,但我我在学习。 The code produces a single different result every time it is ran.该代码每次运行时都会产生一个不同的结果。 The code produces the following error: 26.8 Traceback (most recent call last): File "main.py", line 7, in tot = sum(rand)/len(rand) TypeError: 'float' object is not iterable代码产生以下错误:26.8 Traceback(最近一次调用最后一次):文件“main.py”,第 7 行,in tot = sum(rand)/len(rand) TypeError: 'float' object is not iterable

import random
for x in range (10000):
   rand = random.uniform(10, 100)
   print(round(rand, 1))

   tot = sum(rand)/len(rand)
   print (round(tot, 1))

You're not actually generating a list, you're generating individual values.您实际上不是在生成列表,而是在生成单个值。 Do you really want to print out 10000 values along the way to your final result?您真的想在获得最终结果的过程中打印出 10000 个值吗?

If the answer is "no,": then your code can be reduced to:如果答案是“否”:那么您的代码可以简化为:

import random

N = 10000
print(round(sum(random.uniform(10, 100) for _ in range(N)) / N, 1))

or, if you prefer to break it out a little bit more for readability:或者,如果您更愿意为了可读性而将其拆分一下:

import random

N = 10000
total = sum(random.uniform(10, 100) for _ in range(N))
average = total / N
print(round(average, 1))

If this is beyond the scope of what you've learned, you can create total outside the loop initialized to zero, update it with each new value as you iterate through the loop, and then calculate the final answer:如果这超出了您所学的 scope,您可以在初始化为零的循环外创建total ,在遍历循环时使用每个新值更新它,然后计算最终答案:

import random

N = 10000
total = 0.0
for _ in range(N):     # use '_' instead of x, since x was unused in your prog
    total += random.uniform(10, 100)
average = total / N
print(round(average, 1))

This avoids wasting storage for a list of 10000 values and avoids the append() you're not yet familiar with.这避免了为 10000 个值的列表浪费存储空间,并避免了您还不熟悉的append() Of course, if you need the 10000 values later for some other purpose, you'll need to tuck them away in a list:当然,如果您稍后需要 10000 个值用于其他目的,则需要将它们藏在一个列表中:

import random

N = 10000
l = [random.uniform(10, 100) for _ in range(N)]
total = sum(l)
print(round(total / N, 1))

Addendum附录

Just for jollies, you can also do this recursively:只是为了快乐,您也可以递归地执行此操作:

import random

def sum_of_rands(n):
    if n > 1:
        half_n = n // 2
        return sum_of_rands(half_n) + sum_of_rands(n - half_n)
    elif n == 1:
        return random.uniform(10, 100)

N = 10000
print(round(sum_of_rands(N) / N, 1))
print(sum_of_rands(0))  # returns None because nothing is being summed

Splitting the problem in half (on average) in each recursive call keeps the stack to O(log N).在每个递归调用中将问题分成两半(平均)使堆栈保持为 O(log N)。

I'd actually advise you to stick with list comprehension or looping, but wanted to show you there are lots of different ways to get to the same result.我实际上建议您坚持使用列表理解或循环,但想向您展示有很多不同的方法可以获得相同的结果。

In the sum function you must parse an iterable object but you're parsing a float object.在总和 function 中,您必须解析可迭代的 object,但您正在解析浮点 object。 To avoid this error you should put two last lines outside the for loop and append rand to a list.为避免此错误,您应该将最后两行放在 for 循环和 append rand之外的列表中。 I don't know if it's what you want to do but it shows you how use sum :我不知道这是否是您想要做的,但它向您展示了如何使用sum

import random
l = []
for x in range(10000):
    rand = random.uniform(10, 100)    
    l.append(rand)
    print(round(rand, 1))

tot = sum(l)/len(l)
print(round(tot, 1))

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

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