0

我目前在字典理解中使用列表理解来检测两个以列表为值的字典之间的变化。

代码看起来像这样:

detectedChanges = {table: [field for field in tableDict[table] if field not in fieldBlackList] for table in modifiedTableDict if table not in tableBlackList}

这将创建一个字典,其中每个条目都是表名,并且与之关联的是列表更改。

我遇到的问题是,尽管此代码有效,但生成的结构检测更改充满了仅包含表名和空列表的条目(意味着未检测到更改)。

我目前正在对字典进行后扫描以删除这些条目,但我想首先避免将它们放入字典中。

基本上,如果我能以某种方式进行长度检查或其他事情,[field for field in tableDict[table]我可以在创建 key:value 条目之前对其进行验证。

有没有办法用我正在使用的当前方法做到这一点?

4

2 回答 2

1

尽管 dict 理解很酷,但它们不应该被滥用。下面的代码不会太长,它也可以保存在窄屏幕上:

detectedChanges = {}
for table, fields in modifiedTableDict.iteritems():
    if table not in tableBlackList:
        good_fields = [field for field in fields
                             if field not in fieldBlackList]
        if good_fields:
            detectedChanges[table] = good_fields
于 2015-02-04T16:23:10.557 回答
0

只是对eumiro 回答的补充。请先使用他们的答案,因为它更具可读性。但是,如果我没记错的话,理解通常更快,所以有一个用例,但仅当这是您的代码中的一个瓶颈时。我怎么强调都不过分。

detectedChanges = {table: [field for field in tableDict[table]
                           if field not in fieldBlackList]
                   for table in modifiedTableDict
                   if table not in tableBlackList
                   if set(tableDict[table])-set(fieldBlackList)}

注意这是多么丑陋。我喜欢做这样的事情来更好地理解 Python,并且由于我以前遇到过这样的事情成为瓶颈。但是,在尝试解决可能不存在的问题之前,您应该始终使用分析。

添加到您的代码[...] if set(tableDict[table])-set(fieldBlackList) [...]中会在当前表中创建一组条目,以及一组列入黑名单的字段,并获取当前表中但不在黑名单中的条目。空集评估False导致理解忽略该表,就像它在tableBlackList变量中一样。为了更明确,可以将结果与一个空集进行比较,或者检查它是否有值。

此外,更喜欢以下速度:

detectedChanges = {table: [field for field in fields
                           if field not in fieldBlackList]
                   for table, fields in modifiedTableDict.iteritems()
                   if table not in tableBlackList
                   if set(fields)-set(fieldBlackList)}
于 2015-02-04T16:34:05.180 回答