[英]Python: How would I get an average of a set of tuples?
I have a problem I attempting to solve this problem. 我有一个尝试解决此问题的问题。
I have a function that produces tuples. 我有一个产生元组的函数。 I attempted to store them in an array in this method
我试图用这种方法将它们存储在数组中
while(loops til exhausted)
count = 0
set_of_tuples[count] = function(n,n,n)
count = count + 1
apparently python doesn't store variables this way. 显然python不会以这种方式存储变量。 How can I go about storing a set of tuples in a variable and then averaging them out?
我该如何去将一组元组存储在一个变量中,然后将它们平均化?
You can store them in a couple ways. 您可以通过几种方式存储它们。 Here is one:
这是一个:
set_of_tuples = []
while `<loop-condition>`:
set_of_tuples.append(function(n, n, n))
If you want to average the results element-wise, you can: 如果要按元素对结果进行平均,则可以:
average = tuple(sum(x[i] for x in set_of_tuples) / len(set_of_tuples)
for i in range(len(set_of_tuples[0])))
If this is numerical data, you probably want to use Numpy instead. 如果这是数字数据,则可能要使用Numpy。 If you were using a Numpy array, you would just:
如果您使用的是Numpy数组,则只需:
average = numpy.average(arr, axis=0)
Hmmm, your psuedo-code is not Python at all. 嗯,您的伪代码根本不是Python。 You might want to look at something more like:
您可能想看看更多类似的东西:
## count = 0
set_of_tuples = list()
while not exhausted():
set_of_tuples.append(function(n,n,n))
## count += 1
count = len(set_of_tuples)
However, here the count is superfluous since we can just *len(set_of_tuples)* after the loop if we want. 但是,这里的计数是多余的,因为如果需要的话,我们可以在循环后仅* len(set_of_tuples)*。 Also the name "set_of_tuples" is a pretty poor choice;
同样,“ set_of_tuples”这个名字是一个很差的选择。 especially given that it's not a set.
特别是考虑到它不是一个集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.