James Wilson
James Wilson

Reputation: 942

How to implement a counter for each element of a python list?

Using Python 3.4

I've got a way that works, but I think there might be a better way. I want to have a list with a method expand() which chooses a random element from the list, but every time that element is chosen, a counter is incremented. I tried subclassing str to be able to add attributes but it didn't work.

My main problem with what I've got is that the expression random.randint(0,len(self)-1) and using a local variable doesn't seem very Pythonic. Before I added the counter, I could just type random.choice(self)

class clauses(list):
    def __init__(self):
        self.uses = []

    def __setitem__(self,key,value):
        self.uses[key]=value
        super().__setitem__(self,key,value)

    def __delitem__(self,key):
        del(self.uses[key])
        super().__delitem__(key)

    def append(self,value):
        self.uses.append(0)
        super().append(value)

    def extend(self,sequence):
        for x in sequence:
            self.uses.append(0)
            super().append(x)

    def expand(self):

        n = random.randint(0,len(self)-1)

        self.uses[n] += 1
        return(self[n])

Upvotes: 4

Views: 1580

Answers (1)

DMML
DMML

Reputation: 1452

Initializing an empty dictionary, along with your list should solve this, assuming there are no duplicate entries within the list.

When adding an element to the list, you can also add it to the dictionary by myDict[element]=0 where myDict is the initialized dictionary, and element is the item being added to the list.

Then, when the item is selected, you can simply do: myDict[element]+=1.

When dealing with an instance of duplicate entries, you could create a dictionary of dictionaries in which each key in the dictionary is a word, and the nested dictionary keys for each word are, say, index positions of the duplicate word (the values of course being the actual counts). This does add substantial complication, however, as when you remove an item from your list you will need to also update index positions. This nested data structure would like something like this though: { word1: {position1: count1}, word2: {position1: count1, position 2: count2}....}

Upvotes: 1

Related Questions