The following Python code should make it clear what I would like to execute.
# Say I have the following list and I want to keep count of 1 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]
Please let me know if this is possible or not in order to have a more compact code for this.
Thanks!
[sum([x.count(1) for x in L[:i]]) for i in range(1, len(L) + 1)]
should do what you want.
Use sum and list comprehension.
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))]
Source: https://habr.com/ru/post/1501111/More articles:Is there a BPMN 2.0 Parser for .NET? - .netvisualization - the size of the circle proportional to the value of the element - graphAccording to the TLD or attribute directive in the tag file, the attribute verb does not accept any expressions - javaiOS: when to assign and when to create a new copy of the objects assigned to a property - propertiesWhy is this stack overflow instead of using tail recursion? - clojureDoes tail recursion support shorten the stack for other function calls? - recursionAfter selecting “Cancel” in the “Notification Permissions” dialog, the settings indicate that notification alerts are turned on - iosRefused to run the JavaScript URL because it violates the following content security policy directive: - javascriptMultiple rendering goals in one FBO with different texture sizes? - openglWhy do my Script bindings only work on the server - asp.net-mvc-4All Articles