[英]Python: Comparing values in a defaultdict(set)
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. 我有一个
defalutdict(set)
,它存储一组用户,每个用户一组事件和每个事件的时间戳。 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. 我需要做的是检查defaultdict中项目的时间戳,如果它不在特定时间范围内,则将其从dict中删除。
The defaultdict[player] looks like this: defaultdict [player]看起来像这样:
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 1)如果e> =(curTime-num_seconds),在uniqueFishes [player]中为e的第73行^ SyntaxError:无效语法
2) Set changed size during iteration 2)在迭代过程中设置更改的大小
. 。
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. 将您的if函数放入循环中。
Your e
variable is not a timestamp, but a tuple of a string and a timestamp. 您的
e
变量不是时间戳,而是字符串和时间戳的元组。 You get the timestamp with selecting the 2nd item of the tuple: e[1]
. 通过选择元组的第二项可以得到时间戳:
e[1]
。
You modify an iterable ( uniqueFishes
) while iterating over it. 您可以在迭代时修改一个iterable(
uniqueFishes
)。 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.
最简单(但不是最有效)的解决方案是在修改集合本身的同时迭代原始集合的COPY。
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.