【问题标题】:complicated list and dictionary lookup in pythonpython中复杂的列表和字典查找
【发布时间】:2013-05-09 22:23:47
【问题描述】:

我有一个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'],
}

现在我想查找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, )

【问题讨论】:

    标签: python list dictionary tuples lookup


    【解决方案1】:

    首先,在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)]
    

    【讨论】:

    • 这看起来真的很有效,但是使用列表推导并不能保留排序顺序,因为它会返回一个新的列表对象。我应该在问题中提到保留顺序。不过这很好。
    • @Amyth:列表推导保留了lot 的顺序。你指的是什么顺序?
    • 我的错,确实如此,它使用相同的顺序进行迭代。
    猜你喜欢
    • 1970-01-01
    • 2020-08-09
    • 2021-11-17
    • 2023-01-07
    • 2014-07-21
    • 2021-12-14
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多