2011-09-10 35 views
1

我是Python新手,擁有數字列表。例如 5,10,32,35,64,76,23,53...訪問數組中的分組項

我已經使用this post的代碼將它們分成了四個(5,10,32,35,64,76,23,53等..)。

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") 

如何訪問單個數組以便我可以對它們執行功能。例如,我想得到每個組的第一個數值的平均值(例如我的示例中的數字爲5 and 64)。

回答

2

假設你有以下元組元組:

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

訪問每個元組的第一個元素,用一個for循環:第一個值

for i in a: 
    print i[0] 

計算平均:

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

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

好的,這是yield每次迭代四個數字的元組。因此,轉換整個事情的清單:

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

然後你就會有元組的列表:

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

你可以得到的第一個項目中的每個元組是這樣的:

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

(當然還有其他的方法。)

1

你已經創建了一個元組元組列表,或者列表列表,或者列表元組,或者其他...

您可以訪問元素的任何元素Ÿ直接嵌套列表:

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

您也可以通過循環頂部結構訪問嵌套結構:

for list in lists: 
    print list[y] 
+0

您正在重新定義'list',它是一個標準的類名。不建議。 –

+0

是的,我通常會避免這樣做,但python語法突出顯示有助於示例。 – inlinestyle

1

可能是矯枉過正您的應用程序,但你應該看看我的圖書館,熊貓。像這樣的東西是用的GroupBy功能很簡單:

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

要做到4-AT-A-時間的事情,你需要計算桶裝陣列:

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

然後,它的作爲簡單爲:

data.groupby(buckets).mean()