【问题标题】:Map elements of a list of lists to a dictionary value将列表列表的元素映射到字典值
【发布时间】:2021-10-01 20:37:43
【问题描述】:

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

{'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]

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

【问题讨论】:

  • 您能分享您尝试过的代码示例吗?
  • 您的列表格式不正确,能否解决一下?
  • 你到底试过什么?
  • 我已经回滚了最近的编辑,因为它假设 OP 的数据是以特定方式构造的,而我认为这还不清楚。我认为 OP 负责澄清他们的数据结构。
  • @ddejohn:我想这是有道理的。 很难准确地说出 OP 的结构是什么。

标签: python dictionary


【解决方案1】:

递归处理深入数据:

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 是你的数据。

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2019-05-09
    • 2010-12-31
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多