I have a defalutdict(set)
that stores a set of users, and for each user a set of events, and a timestamp for each event. What I need to do is check the timestamp of the item in the defaultdict and if it falls outside a specific time then remove it from the dict.
The defaultdict[player] looks like this:
set([('event1', <function timestampToEpoch at 0x102f8b758>),
('event3', <function timestampToEpoch at 0x102f8b758>),
('event2', <function timestampToEpoch at 0x102f8b758>)]))
The code I'm trying to use looks like:
def removeUnique(player, f_Type, num_seconds, ts):
curTime = timestampToEpoch(ts)
for e in uniqueFishes[player] if e <= curTime - num_seconds
uniqueFishes[player].remove(e)
print uniqueFishes[player]
As you mentioned the two errors:
1) line 73 for e in uniqueFishes[player] if e >= (curTime - num_seconds) ^ SyntaxError: invalid syntax
2) Set changed size during iteration
.
change
for e in uniqueFishes[player] if e >= curTime - num_seconds
uniqueFishes[player].remove(e)
to :
to_remove_set = set()
for e in uniqueFishes[player]:
if e[1] >= (curTime - num_seconds):
to_remove_set.add(e)
# modify your set after iteration.
uniqueFisihes[player] -= to_remove_set
Put your if function in the loop.
Your e
variable is not a timestamp, but a tuple of a string and a timestamp. You get the timestamp with selecting the 2nd item of the tuple: e[1]
.
You modify an iterable ( uniqueFishes
) while iterating over it. It is always a bad idea. Easiest (but not most efficient) solution for this is to iterate over a COPY of the original set while modifying the set itself.
def removeUnique(player,f_Type,num_seconds,ts):
curTime = timestampToEpoch(ts)
for e in uniqueFishes[player].copy():
if e[1] >= curTime - num_seconds:
uniqueFishes[player].remove(e)
print uniqueFishes[player]
Use a list comprehension:
[uniqueFishes[player].remove(e) for e in uniqueFishes[player]
if e >= (curTime - num_seconds)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.