Drew
Drew

Reputation: 5

python list, working with multiple elements

a is a list filled dynamically with values being received in no specific order. So, if the next value received was (ID2,13), how could I remove the (ID2,10) based on the fact that ID2 was the next value received? Because I don't know the order in which the list is being populated, I won't know the index.

Also, how would I know the count of a specfic ID? I have tried a.count(ID1) but because of the second element, it fails to find any.

a = [(ID1,10),(ID2,10),(ID1,12),(ID2,15)] My current usage:

while True:
    'Receive ID information in format (IDx,Value)'
     ID_info = (ID2,13) #For example
     if a.count(ID2) == 2: #I need to modify this line as it always returns 0
        del a[0] #This is what I need to modify to delete the correct information, as it is not always index 0
    a.append(ID_info)
else:

  a.append(ID_info)        

Upvotes: 0

Views: 154

Answers (1)

Roger Fan
Roger Fan

Reputation: 5045

Assuming that the ID's are hashable, it sounds like you want to be using a dictionary.

a = {ID1: 10, ID2: 10}
id, val = (ID2, 13)
a[id] = val

With the "keep two" addition, I still think it's easier with a dictionary, though with some modifications.

EDIT: Simpler version using collections.defaultdict.

from collections import defaultdict

a = defaultdict(list)
a[ID1].append(10)
a[ID2].append(10)

id, val = (ID2, 13)
a[id].append(val)
if len(a[id]) > 2:
    a[id].pop(0)

def count(a, id):
    return len(a[id])

a = {ID1: [10], ID2: [10]}
id, val = (ID2, 13)

if id not in a.keys():
    a[id] = []

a[id].append(val)
if len(a[id]) > 2:
    a[id].pop(0)

def count(a, id):
    if id not in a.keys():
        return 0
    else:
        return len(a[id])

You could (and probably should) also encapsulate this behavior into a simple class inherited from dict.

Upvotes: 2

Related Questions