繁体   English   中英

Python:比较defaultdict(set)中的值

[英]Python: Comparing values in a defaultdict(set)

我有一个defalutdict(set) ,它存储一组用户,每个用户一组事件和每个事件的时间戳。 我需要做的是检查defaultdict中项目的时间戳,如果它不在特定时间范围内,则将其从dict中删除。

defaultdict [player]看起来像这样:

set([('event1', <function timestampToEpoch at 0x102f8b758>), 
     ('event3', <function timestampToEpoch at 0x102f8b758>),
     ('event2', <function timestampToEpoch at 0x102f8b758>)]))

我尝试使用的代码如下所示:

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]

正如您提到的两个错误:

1)如果e> =(curTime-num_seconds),在uniqueFishes [player]中为e的第73行^ SyntaxError:无效语法

2)在迭代过程中设置更改的大小

更改

for e in uniqueFishes[player] if e >= curTime - num_seconds
        uniqueFishes[player].remove(e)

至 :

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

将您的if函数放入循环中。

您的e变量不是时间戳,而是字符串和时间戳的元组。 通过选择元组的第二项可以得到时间戳: e[1]

您可以在迭代时修改一个iterable( uniqueFishes )。 这总是一个坏主意。 最简单(但不是最有效)的解决方案是在修改集合本身的同时迭代原始集合的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]

使用列表理解:

[uniqueFishes[player].remove(e) for e in uniqueFishes[player] 
 if e >= (curTime - num_seconds)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM