简体   繁体   English

Python - 枚举过滤字典的非笨拙方式

[英]Python - non-clumsy way to enumerate over filtered dictionary

I have a code like this ( d is some dictionary and s is some set):我有这样的代码( d是一些字典, s是一些集合):

for i, (k, v) in enumerate((k, v) for k, v in d.items() if k in s):
    ...

Even if we ignore the ugly repetition, all literals actually have substantial length, so repeating k and v 3 times is not an option.即使我们忽略丑陋的重复,所有文字实际上都有相当长的长度,因此重复kv 3 次不是一种选择。 What's the best way to write it?最好的写法是什么? Right now, we use the following (also ugly) option:现在,我们使用以下(也是丑陋的)选项:

i = -1
for k, v in d.items():
    if k not in s:
        continue
    i += 1
    ...

Another option:另外的选择:

for i, (k, v) in enumerate((k, d[k]) for k in d if k in s):
    ...

, but it basically has the same amount of repetitions. ,但它基本上具有相同的重复次数。

I'm OK with using any library which is shipped by default (ie without pip install ).我可以使用默认提供的任何库(即没有pip install )。

With one extra line, but much less complexity, you could do:使用额外的一行,但复杂性要低得多,您可以执行以下操作:

for i, k in enumerate(filter(s.__contains__, d)):
    v = d[k]

A variation of this uses set intersection (that may scramble your insertion order though):这种方法的一种变体是使用集合交集(虽然这可能会扰乱您的插入顺序):

for i, k in enumerate(s & d.keys()):
    v = d[k]

dict comprehension is the fastest way to filter a dict: dict理解是过滤dict的最快方法:

filtered_dict = {key: value for key, value in d.items() if key in s}

Therefore, I would suggest to define a task function that does the job on the items and do everything inside this dict comprehension:因此,我建议定义一个任务 function 来完成项目的工作并在这个字典理解中做所有事情:

def task(key, value):
    # do the required job on the dict items
    ....
    return result


{key: task(key, value) for key, value in d.items() if key in s}

The result is a dict that contains the computed result for each key/value item.结果是一个字典,其中包含每个键/值项的计算结果。 Of, course, you can add enumerate if an index is required in addition.当然,如果额外需要索引,您可以添加enumerate

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

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