Nested List and count()
Here is yet another approach to flatten a nested sequence. Once the sequence is flattened it is an easy check to find count of items.
def flatten(seq, container=None):
if container is None:
container = []
for s in seq:
try:
iter(s) # check if it's iterable
except TypeError:
container.append(s)
else:
flatten(s, container)
return container
c = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]])
print(c)
print(c.count('g'))
d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]])
print(d)
print(d.count(1))
The above code prints:
[1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
1
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
12
Count occurrences of list element in nested list
This is probably most easily achieved just using a Counter
on the first element of each list:
from collections import Counter
c =Counter([l[0] for l in list_all])
list(c.items())
Output:
[('car', 3), ('bicycle', 2), ('taxi', 3), ('motorcycle', 4)]
If you really want a list of lists (as opposed to a list of tuples) in the output, use a list comprehension over c.items()
:
[list(i) for i in c.items()]
Output:
[['car', 3], ['bicycle', 2], ['taxi', 3], ['motorcycle', 4]]
Recursively counting occurrences in a nested list of numbers
def count(lst, target):
n = 0
for i in lst:
if i == target:
n += 1
elif type(i) is list:
n += count(i, target)
return n
Counting number of elements in nested list
If you're looking for the number of authors per year, you could use this:
# Authors per year
authors_per_year = { year: len(authors) for year, authors in the_list }
Gives you this:
{1940: 5, 1941: 9, 1942: 9, 1943: 6, 1944: 1}
Or, if you looking for a count of unique authors then you could use this:
# Unique authors
unique_authors = set([ a for year, authors in the_list
for a in authors])
Gives you this set:
set(['Bousfield G',
'Bruner DW',
'Burr GO',
'Crawford GN',
'Dong L',
'Edwards PR',
'Faber HK',
'Fishbein M',
'Gaffron H',
'Gardner FT',
'Gates RR',
'Gould BS',
'Greene HS',
'Haas O',
'Hatch MH',
'Hill DK',
'Howorth MB',
'Hughes H',
'Lake NC',
'Lewis WH',
'McClung CE',
'Myers J',
'Ratner B',
'Ritter WE',
'Rubin J',
'Silverberg RJ',
'Sumner FB',
'Tytell AA'])
So len(unique_authors)
gives you a count of 28
.
In any case, I think the way forward for you may well be to use some combination of list comprehensions or dict comprehension.
Count the number of terms that are not atoms in a nested list
One possible solution would be the following:
count(C) :-
findall(X, vehicle(_, blue, X), Ls),
countOpt(Ls, 0, C).
countOpt([], X, X) :- !.
countOpt([H|T], C, NewC) :-
countOpt(T, C, NewC1),
findall(Opt, member(optional(Opt), H), Opts),
printOpts(Opts),
length(Opts, Length),
NewC is NewC1 + Length, !.
printOpts([]).
printOpts([H|T]) :-
print(H),
nl,
printOpts(T).
As in your approach, first gather all lists of features (I guess?) for each vehicle and save it in a List of lists called Ls
.
Then select in each sublist of Ls
all Optional values (Opt
) and add all the lengths of them.
I also added the predicate to print the results.
How to count a nested collection in a List with Java Streams
I think you are looking for something like
artifactList.stream()
.flatMap(artifact -> artifact.getFindings().stream())
.filter(finding -> finding.isChecked())
.count();
Calculate count of all the elements in nested list
Here is one way.
from collections import Counter
from itertools import chain
test = [["P1", "P1", "P1", "P2", "P2", "P1", "P1", "P3"],
["P1", "P1", "P1"],
["P1", "P1", "P1", "P2"],
["P4"],
["P1", "P4", "P2"],
["P1", "P1", "P1"]]
c = Counter(chain.from_iterable(test))
for k, v in c.items():
print(k, v)
# P1 15
# P2 4
# P3 1
# P4 2
For output as dataframe:
df = pd.DataFrame.from_dict(c, orient='index').transpose()
# P1 P2 P3 P4
# 0 15 4 1 2
Related Topics
What Determines Which Strings Are Interned and When
When Are Objects Garbage Collected in Python
Tkinter Vanishing Photoimage Issue
Differencebetween .Quit and .Quit in Pygame
How to Count the Nan Values in a Column in Pandas Dataframe
A Tool to Convert Matlab Code to Python
Progress Indicator During Pandas Operations
Ssl Insecureplatform Error When Using Requests Package
Adding a Legend to Pyplot in Matplotlib in the Simplest Manner Possible
Super() Raises "Typeerror: Must Be Type, Not Classobj" for New-Style Class
Is the Single Underscore "_" a Built-In Variable in Python
How to Determine the Length of Lists in a Pandas Dataframe Column
Replace All Occurrences of a String in a Pandas Dataframe (Python)
How to Get All the Contiguous Substrings of a String in Python