Python: Counting occurrence of List element within List

I’m trying to count occurrence of elements within a list, if such elements are also lists. The order is also important

[PSUEDOCODE]

list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]
print( count(list) )


> { ['a', 'b', 'c'] : 2, ['d', 'e', 'f']: 1, ['c', 'b', 'a']: 1 }

One important factor is that ['a', 'b', 'c'] != ['c', 'b', 'a']

I have tried:

from collections import counter
print( Counter([tuple(x) for x in list]) )
print( [[x, list.count(x)] for x in set(list)] )

Which both resulted in ['a', 'b', 'c'] = ['c', 'b', 'a'], one thing i didn’t want

I also tried:

from collections import counter
print( Counter( list ) )

Which only resulted in error; since lists can’t be used as keys in dicts.

Is there a way to do this?

Solution:

You can’t have list as a key to the dict because dictionaries only allows immutable objects as it’s key. Hence you need to firstly convert your objects to tuple. Then you may use collection.Counter to get the count of each tuple as:

>>> from collections import Counter
>>> my_list = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['a', 'b', 'c'], ['c', 'b', 'a'] ]

#            v to type-cast each sub-list to tuple
>>> Counter(tuple(item) for item in my_list)
Counter({('a', 'b', 'c'): 2, ('d', 'e', 'f'): 1, ('c', 'b', 'a'): 1})

Create a resource between 0 and N times terraform

The common way this seems to get done, is via something like count = "${length(split(",", var.private_subnets))}" However, this results in either needing trailing commas, or being unable to handle the 0 case:

Eg:

  • ${length(split(",", ""))} is 1
  • ${length(split(",", "foo"))} is 1
  • ${length(split(",", "foo,bar"))} is 2
  • ${length(split(",", "")) -1 } is 0
  • ${length(split(",", "foo")) - 1} is 0
  • ${length(split(",", "foo,")) - 1} is 1
  • ${length(split(",", "foo,bar")) - 1} is 1

neither of those is very satisfying

the compact function was somewhat recently added to deal with empty strings when splitting so, for example:

  • ${length(compact(split(",", "")))} should be 0
  • ${length(compact(split(",", "foo")))} should be 1
  • ${length(compact(split(",", "foo,bar")))} should be 2