首页 > 解决方案 > 将列表列表的元素映射到字典值

问题描述

问题很简单,我有一本字典,其中有分类和分配给标识的编号,例如:

{'checkbox': 0,
 'radio': 1,
 'dropdown': 2,
 'listbox': 3,
 'button': 4,
 'link': 5,
 'input': 6,
 'label': 7}

问题是,该列表由具有这些键值的其他不同长度的列表组成,例如:

[['link',
'dropdown',
'dropdown',
 ['input', 'link'], ['input', 'button', 'link'],
 ['dropdown',
  'button'],...

它非常不规则,因为它与边界框注释有关。所以我的目标是使用地图功能和列表推导。

# Simply using replace method -> know that, these list of labels is a dataframe column
labels_remapped = df['labels'].replace(Dict)

# Using map(Dictionary, iterable)
labels_remapped = map(Dict, df['labels'])

# Iterating over sublists
labels_remapped = [map(Dict, sublist) for sublist in labels]

然而,我没有成功。我怎样才能遍历这个特定的列表并用它的相应值替换?

标签: pythondictionary

解决方案


递归处理深入数据:

def deep_map(func, xs):
    if not isinstance(xs, list):
        return func(xs)
    return [deep_map(func, x) for x in xs]

deep_map(lambda x: d[x], xs)

...哪里d是字典,xs是您的数据。


推荐阅读