a是动态填充的列表,其中没有按特定顺序接收值。那么,如果收到的下一个值是(ID2,13),我怎么能根据ID2是下一个接收值的事实删除(ID2,10)?因为我不知道列表的填充顺序,所以我不知道索引。
另外,我怎么知道specfic ID的数量?
我试过a.count(ID1)
,但由于第二个元素,它找不到任何。
a = [(ID1,10),(ID2,10),(ID1,12),(ID2,15)]
我目前的用法:
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)
答案 0 :(得分:2)
假设ID是可以播放的,听起来你想要使用字典。
a = {ID1: 10, ID2: 10}
id, val = (ID2, 13)
a[id] = val
"保持两个"此外,我仍然认为使用字典会更容易,但需要进行一些修改。
编辑:使用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])
您可以(也可能应该)将此行为封装到从dict
继承的简单类中。