【问题标题】:Count elements in nested list计算嵌套列表中的元素
【发布时间】:2013-09-11 18:38:06
【问题描述】:

下面的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]

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

谢谢!

【问题讨论】:

    标签: python list count mapping nested


    【解决方案1】:
    [sum([x.count(1) for x in L[:i]]) for i in range(1, len(L) + 1)]
    

    应该做你想做的。

    【讨论】:

      【解决方案2】:

      使用sum 和列表理解。

      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]]
      L2 = [sum(x) for x in L]
      T = [sum(L2[:x+1]) for x in xrange(len(L2))]
      

      【讨论】:

        猜你喜欢
        • 2018-07-25
        • 1970-01-01
        • 2021-12-03
        • 2012-08-03
        • 2015-04-20
        • 2019-03-27
        • 1970-01-01
        • 2012-05-22
        • 2021-02-09
        相关资源
        最近更新 更多