python - 将列表列表的元素映射到字典值
问题描述
问题很简单,我有一本字典,其中有分类和分配给标识的编号,例如:
{'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]
然而,我没有成功。我怎样才能遍历这个特定的列表并用它的相应值替换?
解决方案
递归处理深入数据:
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
是您的数据。
推荐阅读
- reactjs - 将 non-create-react-app React 项目部署到 Github Pages 时出现问题
- python - 搜索中的 Visual Studio Code 键绑定
- javascript - 我如何从输入值文本中获取?
- web2py - 我可以使用虚拟字段在 web2py 中显示链接表的值吗?
- json - 将属性添加到反序列化 Json 类
- function - 闭包函数 - 返回全局变量?
- apache-kafka - 为什么卡夫卡不适合我?
- excel - 使用下拉列表过滤 Excel 表格
- python - 在 Python 中将分类值列转换为其统计值
- javascript - 在 PhantomJS/Sinon 中存根 Promise