Python: count overall elements in list of lists
I want to write a function that takes a list of numbers and lists, which again can contain numbers and lists, and so on..., and returns the overall amount of numbers that are somewhere in the list.
[1,[[[0,2],7,3],5,[1,2]],3] contains 9 numbers in it.
This is my code so far:
test=[1,[[[0,2],7,3],5,[1,2]],3] def flatten(mylist): counter = 0 for i in range(len(mylist)): if type(mylist[i]) == int: counter += 1 if type(mylist[i]) == list: [item for sublist in mylist[i] for item in sublist] counter += 1 return counter
I think I need to recursivley flatten the sublists. But I get the error:
TypeError: 'int' object is not iterable
def count_ints_in_list(int_list): def count(n): if isinstance(n, int): # If it is an integer, add 1 to the count. return 1 elif isinstance(n, str): # Ignore strings. return 0 elif hasattr(n, '__iter__'): # If it is iterable, recursively call function. return count_ints_in_list(n) return 0 if not hasattr(int_list, '__iter__'): return 0 return sum(count(n) for n in int_list) # Use a generator to sum the count of all integers. >>> count_ints_in_list(test) 9 >>> count_ints_in_list('test') 0 # Works with lists, tuples, other non-string iterables. >>> count_ints_in_list([1, [[(0,2), 7, 3], 5, (1,2)], 3]) 9
Python : How to Check if an item exists in list ?, How do you count all the elements in a list in Python? Python. # List of lists listOfElems2D = [ [1,2,3,45,6,7], [22,33,44,55], [11,13,14,15] ] # Iterate over the list and add the size of all internal lists count = 0 for listElem in listOfElems2D: count += len (listElem) print ('Total Number of elements : ', count) 1. 2.
a general approach would be to first test an item whether it is iterable. Unfortunately for this,
str objects are iterable, while in most cases, they should count as one item, so should not be flattened. This method can be used for this test:
def is_iterable(item): """tests whether `item` is an iterable that is not a string""" try: iter(item) return not isinstance(item, str) except TypeError: return False
Then you can use generators and recursion to flatten the iterable:
def flatten(iterable): for item in iterable: if is_iterable(item): yield from flatten(item) else: yield item list(flatten([1,[[[0,2],7,3],5,[1,2]],3] ))
[1, 0, 2, 7, 3, 5, 1, 2, 3]
Then you just need another test, the built-in
sum and the fact
True counts as 1 and
False as 0
sum(isinstance(item, int) for item in flatten(mylist))
How do you sum a list of a list in Python? Python | Program to count number of lists in a list of lists Given a list of lists, write a Python program to count the number of lists contained within the list of lists.
To count the elements you don't need to flatten the list. Simply
def count(lst): try: return sum(count(item) for item in lst) except TypeError: return 1
Note that it is a common approach in python to assume the object is iterable, and treat it as such, instead of checking
isinstance(my_list, list) ("easier to ask for forgiveness than permission").
How do you count the number of elements in an array in Python? Python: count overall elements in list of lists. Refresh. December 2018. Views. 62 time. 1. I want to write a function that takes a list of numbers and lists, which
How do you check if something is in a list Python? Example 1: Make a function for both lists. If there are common elements in both the list, then it will return common elements in list c. If both lists do not contain any common elements then it will return an empty list. a=[2,3,4,5] b=[3,5,7,9] def common(a,b): c = [value for value in a if value in b] return c d=common(a,b) print(d) Both the
Use a for loop and in every iteration to check if the type of the current item is a list or not, and accordingly increment 'count' variable. This method has a benefit over There can be any number of words per list, and there can be any number of lists. So I can end up with uneven sets of any number. I know I can compare two sets using the intersection methods, but how do I compare across multiple sets to return only the common items?
Count the number of lists containing x. Initialize count to 0, then start a for loop and check if x exists in each list or not. If yes, increment count. You can use groupby from itertools package if the list is an ordered list. a = [1,1,1,1,2,2,2,2,3,3,4,5,5] from itertools import groupby [len(list(group)) for key, group in groupby(a)] Output: [4, 4, 2, 1, 2] share. Share a link to this answer. Copy link.