python - 如何有效地从字典列表中过滤数据

标签 python python-2.7 dictionary

我在 tuple_listdictionaries_list 中有数据,在这两个列表中都有数千条记录。 我想根据 tuple_list 中的记录从 dictionaries_list 中过滤数据。目前,我编写了以下代码,但是对于元组列表中的每个元素,它都需要花费大量时间来迭代整个字典列表。

# tuple_list can be like [(('s', 45), ('t', 30)), (('s', 5), ('t', 3))]
for target_tuple in tuple_list:
    # target_tuple can have data like (('s', 45), ('t', 30))
    # dictionaries_list can have data like [{'a': 5, 's': 45, 't': 10}, {}, {}]
    if some_parameter == 'something':
        m1_dicts = [d for d in dictionaries_list if d['s'] == target_tuple[0][1]]
    else:
        m1_dicts = [d for d in dictionaries_list if d['t'] == target_tuple[0][1]]

请提出一些改进方法。

最佳答案

据我了解,如果在字典中发现任何 tuple_list 匹配,您想要保留字典。 它确实在运行时有所改进,因为它只运行一次 tuple_list ,但可能不是最好的优化,因为它仍然需要遍历字典列表

# taking small dataset as example
tuple_list=[(('s', 45), ('t', 30)), (('s', 5), ('t', 6))]
dictionaries_list = [{'a': 5, 's': 45, 't': 10}, {'s':5,'t':6}, {'a':2,'s':22,'t':30}]

tuple_dict = {}
tuple_dict['s'] = [i[0][1] for i in tuple_list]
tuple_dict['t'] = [i[1][1] for i in tuple_list]
if some_parameter == 'something':
    # check for 's'
    m1_dicts = [d for d in dictionaries_list if d['s'] in tuple_dict['s']]
    # m1_dicts = [{'a': 5, 's': 45, 't': 10}, {'s':5,'t':6}]
else:
    # check for 't'
    m1_dicts = [d for d in dictionaries_list if d['t'] in tuple_dict['t']]
    # m1_dicts = [{'s':5,'t':6}, {'a':2,'s':22,'t':30}]

代替 some_parameter = 'something',建议使用 some_patameter 作为检查的关键

some_parameter = 's' # check for 's'
m1_dicts = [d for d in dictionaries_list if d[some_parameter] in tuple_dict[some_parameter]]

关于python - 如何有效地从字典列表中过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488004/

相关文章:

python - 对字典中的值执行标准偏差

python - 按一列分组并找到编号。另一列中的唯一值

python - 一定时间后继续 for 循环

python - 从嵌套字典到扁平化数据框

arrays - 合并嵌套的 Yaml 数组

python - 限制从 python 生成器获取的项目数量

python - 在 Python 中验证数字序列是否满足特定条件

python - 允许 python 包要求在设置中失败

python - 从 Tumblr Api 获取视频 url

python-2.7 - 如何在 TensorFlow 中混合基于队列和基于提要的输入