简体   繁体   English

python中复杂的列表和字典查找

[英]complicated list and dictionary lookup in python

I have a list of tuples and a dictionary of lists as follows. 我有一个list of tuples和一个dictionary of lists如下。

# List of tuples
lot = [('Item 1', 43), ('Item 4', 82), ('Item 12', 33), ('Item 10', 21)]

# dict of lists
dol = {

    'item_category_one': ['Item 3', 'Item 4'],
    'item_category_two': ['Item 1'],
    'item_category_thr': ['Item 2', 'Item 21'],
}

Now I want to do a look-up where any item in any list within dol exists in any of the tuples given in lot . 现在,我想做一个查找其中内任何列表中的任何项目dol存在于任何给出的元组的lot If this requirement is met, then i want to add another variable to that respective tuple. 如果满足此要求,那么我想将另一个变量添加到相应的元组。

Currently I am doing this as follows (which looks incredibly inefficient and ugly). 目前我这样做如下(看起来非常低效和丑陋)。 I would want to know the most efficient and neat way of achieving this. 我想知道实现这一目标的最有效和最简洁的方法。 what are the possibilities ? 有什么可能性?

PS: I am also looking to preserve the order of lot while doing this. PS:我也希望在这样做的同时保持lot顺序。

merged = [x[0] for x in lot]

for x in dol:
    for item in dol[x]:
        if item in merged:
            for x in lot:
                if x[0] == item:
                    lot[lot.index(x)] += (True, )

First, build a set of all your values inside of the dol structure: 首先,在dol结构中构建一组所有值:

from itertools import chain
dol_values = set(chain.from_iterable(dol.itervalues()))

Now membership testing is efficient, and you can use a list comprehension: 现在,成员资格测试很有效,您可以使用列表理解:

[tup + (True,) if tup[0] in dol_values else tup for tup in lot]

Demo: 演示:

>>> from itertools import chain
>>> dol_values = set(chain.from_iterable(dol.itervalues()))
>>> dol_values
set(['Item 3', 'Item 2', 'Item 1', 'Item 21', 'Item 4'])
>>> [tup + (True,) if tup[0] in dol_values else tup for tup in lot]
[('Item 1', 43, True), ('Item 4', 82, True), ('Item 12', 33), ('Item 10', 21)]

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

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