Reputation: 1460
am trying to get the length of list and their count in a given list
for ex:
l1 = [['a', 'b', 'c'],['c', 'd', 'f'],['g', 'h', 't', 'j']]
output:
a_3 = 2
b_4 = 1
Upvotes: 0
Views: 49
Reputation: 8318
Another solution using collections.Counter
is:
from collections import Counter
l = [['a', 'b', 'c'], ['c', 'd', 'f'], ['g', 'h', 't', 'j']]
counts = Counter(map(len,l))
map
will iterate over the nested lists inside l
and apply len
to each of them, then Counter
will save each returned length as key and the amount of repetition of that length.
Upvotes: 4
Reputation: 2767
You can streamline things a bit more by using a defaultdict
from collections import defaultdict
list_of_lists = [['a', 'b', 'c'],['c', 'd', 'f'],['g', 'h', 't', 'j']]
list_counter = defaultdict(int)
for one_list in list_of_lists:
list_counter[len(one_list)] += 1
print(list_counter)
defaultdict(<class 'int'>, {3: 2, 4: 1})
Upvotes: 0
Reputation: 9600
You can iterate over the list elements and create a dictionary with counts as:
l1 = [['a', 'b', 'c'], ['c', 'd', 'f'], ['g', 'h', 't', 'j']]
res = dict()
for k in l1:
if len(k) not in res:
res[len(k)] = 1
else:
res[len(k)] += 1
print(res)
Output:
{3: 2, 4: 1}
Upvotes: 2
Reputation: 1460
a_4 = 0
a_3 = 0
for i in mylist:
if len(i) == 4:
a_4 += 1
else:
a_3 += 1
Upvotes: 0