python - 计算嵌套列表中的元素

标签 python list count mapping nested

下面的 python 代码应该清楚我想要完成什么。

# Say I have the following list and I want to keep count of 1's while going through each nested list
L = [[1,1,0,0,0,1],[1,1,0,0,0,0],[0,0,0,0,0,1],[1,1,1,1,1,1]]

# So I'd like to get a list containing [3, 5, 6, 12]
# I tried to find a compact way of doing this by mapping this list into a another list like such 
T = [L[:i].count(1) for i in range(len(L))]
# >>> [0, 0, 0, 0]


# But this doesn't work so how to count occurances for nested lists?
# Is there a compact way of doing this (maybe with Lambda functions)?

# I'd like to avoid using a function like:
def Nested_Count():
    Result = []
    count = 0
    for i in L:
        count += i.count(1)
        Result.append(count)
    return Result
# >>> [3, 5, 6, 12]

请让我知道是否可以使用更紧凑的代码来执行此操作。

谢谢!

最佳答案

[sum([x.count(1) for x in L[:i]]) for i in range(1, len(L) + 1)]

应该做你想做的。

关于python - 计算嵌套列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18678486/

相关文章:

python - 如何在 NumPy 中将 2d 数组的值分配给 3d 数组

list - 在 Prolog 的第 N 个位置拆分列表的更简单方法?

c - 列表阅读不显示最后一个条目

javascript - 列表项数组上的 Onclick 事件

R:如何根据时间和日期查找计数

python - tf.constant 与 tf.placeholder

python - 动态创建对象的 Doctest

python - stem - 无法通过 tor 使用 python 获取新的 ip

excel - 我怎样才能让它从第41行开始呢?

mysql - 一个查询上有两个单独的联接;对发往和来自一位用户的所有消息进行计数