Python 如何创建一个计算列表中两个数的函数?

Python 如何创建一个计算列表中两个数的函数?,python,list,function,Python,List,Function,如何创建一个计算聚合二的数量并返回元组的函数 像这样: t=[2,2,3,3,3,4,3,4,2,2,2,2,2] # in this example we have 2 twos, other numbers, and more 5 twos counts_two(t) # returns (2, 5) t=[2,2,2,3,4,5,6,7,5,4,2,2,4,5,2] # in th

如何创建一个计算聚合二的数量并返回元组的函数

像这样:

t=[2,2,3,3,3,4,3,4,2,2,2,2,2]     # in this example we have 2 twos, other numbers, and more 5 twos
counts_two(t)                   
# returns (2, 5)                               

t=[2,2,2,3,4,5,6,7,5,4,2,2,4,5,2] # in this example we have 3 twos, other numbers, then 2 twos, followed by other numbers, and more 1 two
counts_two(t)
#returns (3, 2, 1)

此函数
M
将对一组值进行计数。它以以下格式输出组出现的列表:[组索引,组长度]

它使用标志
m
来跟踪组内/组外。如果退出,则开始新的组引用;如果加入,则增加组长度。它沿着列表向下移动并测试值的相等性

t=[2,2,3,3,3,4,3,4,2,2,2,2,2]
j=[2,2,2,3,4,5,6,7,5,4,2,2,4,5,2]

def M(L, N):
    c = []
    m = 0
    for i,n in enumerate(L):
        if n == N:
            if m:
                c[-1][1] += 1
            else:
                c.append([i, 1])
            m = 1
        else:
            m = 0
    return c

print M(t, 2)
print M(j, 2)
输出:

[[0, 2], [8, 5]]
[[0, 3], [10, 2], [14, 1]]

groupby
是一个可能对您有帮助的功能。我认为您获得了很多反对票,因为您还没有真正记录您所做的尝试。也许如果你演示了一两件你尝试过的事情,你可能会得到一些有用的回答。你的问题是什么?
[sum(i==i代表i在val中)代表key,val在groupby(列表)中代表key==2]