基于字典内部值的映射列表。

huangapple go评论86阅读模式
英文:

map list based on dict internal values

问题

我有一个类似的列表:

[{'sample': {'sample_context': {'board': u'9', 'encoder': u'1'}, 18421: u'1191'}}, {'sample': {'sample_context': {'board': u'5', 'encoder': u'1'}, 18422: u'2251'}}, {'sample': {'sample_context': {'board': u'9', 'encoder': u'1'}, 18423: u'2291'}}, {'sample': {25680: u'3321', 'sample_context': {'board': u'2', 'encoder': u'1'}}}, {'sample': {'sample_context': {'board': u'9', 'encoder': u'1'}, 29100: u'5591'}}]

我如何基于sample_context字段将值分离出来?

我尝试了以下方法,但不起作用,我认为我需要根据sample_context字段映射值:

[sample_sent['sample'] for sample_sent in x]

目标是给我提供所有带有特定上下文的值,比如:{'board': u'9', 'encoder': u'1'}

英文:

I have a list like:

[{'sample': {'sample_context': {'board': u'9', 'encoder': u'1'}, 18421: u'1191'}}, {'sample': {'sample_context': {'board': u'5', 'encoder': u'1'}, 18422: u'2251'}}, {'sample': {'sample_context': {'board': u'9', 'encoder': u'1'}, 18423: u'2291'}}, {'sample': {25680: u'3321', 'sample_context': {'board': u'2', 'encoder': u'1'}}}, {'sample': {'sample_context': {'board': u'9', 'encoder': u'1'}, 29100: u'5591'}}]

How could I separate values i.e. 18421: u'1191', 18422: u'2251' etc based per sample_context field

I tried to do but it doesn't work, I think I need to map values based on sample_context field

[sample_sent['sample'] for sample_sent in x]

The goal is to answer give me all the values with context lets say: {'board': u'9', 'encoder': u'1'}

答案1

得分: 1

类似以下的理解将提取这样的映射:

{k:v for d in lst for d2 in d.values() for k,v in d2.items() if isinstance(k,int)}
# {18421: '1191', 18422: '2251', 18423: '2291', 25680: '3321', 29100: '5591'}
英文:

Something like the following comprehension will extract such a mapping:

{k:v for d in lst for d2 in d.values() for k,v in d2.items() if isinstance(k,int)}
# {18421: '1191', 18422: '2251', 18423: '2291', 25680: '3321', 29100: '5591'}

huangapple
  • 本文由 发表于 2023年7月13日 18:18:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定