我是 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 和 64
)。
最佳答案
假设您有以下元组元组:
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))
关于python - 访问数组中的分组项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7374523/