簡體   English   中英

python中復雜的列表和字典查找

[英]complicated list and dictionary lookup in python

我有一個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, )

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM