python - 访问数组中的分组项目

标签 python arrays list grouping

我是 Python 新手,有一个数字列表。例如 5,10,32,35,64,76,23,53...

我使用 this post 中的代码将它们分成四组(5,10,32,3564,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/

相关文章:

python - 用条纹数替换字符串

python - 用另一个列表切片列表

python - lark 语法 : How does the escaped string regex work?

python - 从按日期/名称分组的单独目录中的 JPEG 生成 PDF

python - 如何加载现有的 ipython 笔记本?

java - 如何在方法中声明数组

java - 如何以图形方式重绘字符串数组而不与文本重叠?

arrays - ScalaTestFailureLocation 预期的 StructField(value1,ArrayType(StringType,true),false) 实际的 StructField(val2,ArrayType(StringType,true),true)

python - 对列表中的列表中的字典进行列表理解

python - Django 中的 Meta 到底是什么?