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

标签 python list dictionary tuples lookup

我有一个元组列表和一个列表字典,如下所示。

# 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'],
}

现在我想查找 dol 中任何列表中的任何项目是否存在于 lot 中给出的任何元组中。如果满足此要求,那么我想向相应的元组添加另一个变量。

目前我正在这样做(看起来非常低效和丑陋)。我想知道实现此目标的最高效简洁 方法。有哪些可能性?

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, )

最佳答案

首先,在 dol 结构中构建一组所有值:

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

现在成员资格测试很有效,您可以使用列表理解:

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

演示:

>>> 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)]

关于python - python中复杂的列表和字典查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563494/

相关文章:

python - 从 pandas.core.series.Series 中删除前导零

python - 插入表时处理 SQLAlchemy 中的触发器

c++ - map 声明未编译

python - 确定嵌套对象是否在列表中

python - 惰性延迟列表达到最大递归深度

python - 将 EC2 与自动缩放组一起用于 AWS 上的批量图像处理应用程序

python - 从嵌套列表中提取数据

java - Java 中通过键连接字符串值的最方便的习惯用法

c++ - C++ 中带有继承类的链表?

python - 过滤包含特定字符串的列表