我有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
中任何元组中lot
内任何列表中的任何项目。如果满足此要求,那么我想将另一个变量添加到相应的元组。
目前我正在按照以下方式执行此操作(看起来非常低效和丑陋)。我想知道实现这一点的高效和整洁方式。有什么可能性?
PS:我还希望在执行此操作时保留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, )
的顺序。
{{1}}
答案 0 :(得分:5)
首先,在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)]