Skoder
Skoder

Reputation: 4053

Accessing grouped items in arrays

I'm new to Python and have a list of numbers. e.g. 5,10,32,35,64,76,23,53....

and I've grouped them into fours (5,10,32,35, 64,76,23,53 etc..) using the code from this post.

def group_iter(iterator, n=2, strict=False):
    """ Transforms a sequence of values into a sequence of n-tuples.
    e.g. [1, 2, 3, 4, ...] => [(1, 2), (3, 4), ...] (when n == 2)
    If strict, then it will raise ValueError if there is a group of fewer
    than n items at the end of the sequence. """
    accumulator = []
    for item in iterator:
        accumulator.append(item)
        if len(accumulator) == n: # tested as fast as separate counter
            yield tuple(accumulator)
            accumulator = [] # tested faster than accumulator[:] = []
            # and tested as fast as re-using one list object
    if strict and len(accumulator) != 0:
        raise ValueError("Leftover values")

How can I access the individual arrays so that I can perform functions on them. For example, I'd like to get the average of the first values of every group (e.g. 5 and 64 in my example numbers).

Upvotes: 1

Views: 178

Answers (4)

Wes McKinney
Wes McKinney

Reputation: 105501

Might be overkill for your application but you should check out my library, pandas. Stuff like this is pretty simple with the GroupBy functionality:

http://pandas.sourceforge.net/groupby.html

To do the 4-at-a-time thing you would need to compute a bucketing array:

import numpy as np
bucket_size = 4
n = len(your_list)
buckets = np.arange(n) // bucket_size

Then it's as simple as:

data.groupby(buckets).mean()

Upvotes: 1

inlinestyle
inlinestyle

Reputation: 127

You've created a tuple of tuples, or a list of tuples, or a list of lists, or a tuple of lists, or whatever...

You can access any element of any nested list directly:

toplist[x][y] # yields the yth element of the xth nested list

You can also access the nested structures by iterating over the top structure:

for list in lists:
    print list[y]

Upvotes: 1

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

Let's say you have the following tuple of tuples:

a=((5,10,32,35), (64,76,23,53)) 

To access the first element of each tuple, use a for-loop:

for i in a:
     print i[0]

To calculate average for the first values:

elements=[i[0] for i in a]

avg=sum(elements)/float(len(elements))

Upvotes: 2

Tom Zych
Tom Zych

Reputation: 13576

Ok, this is yielding a tuple of four numbers each time it's iterated. So, convert the whole thing to a list:

L = list(group_iter(your_list, n=4))

Then you'll have a list of tuples:

>>> L
[(5, 10, 32, 35), (64, 76, 23, 53), ...]

You can get the first item in each tuple this way:

firsts = [tup[0] for tup in L]

(There are other ways, of course.)

Upvotes: 1

Related Questions