简体   繁体   中英

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. 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. If you were using a Numpy array, you would just:

average = numpy.average(arr, axis=0)

Hmmm, your psuedo-code is not Python at all. 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. Also the name "set_of_tuples" is a pretty poor choice; especially given that it's not a set.

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