英文:
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'}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论