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

我有一个元组列表和一个列表字典如下.

# 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中任何列表中任何元素中存在的任何元组中的任何元素.如果满足此要求,那么我想将另一个变量添加到相应的元组.

目前我这样做如下(看起来非常低效和丑陋).我想知道实现这一目标的最有效和最简洁的方法.有什么可能性?

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

解决方法:

首先,在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,dictionary,tuples,lookup,list

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值