简体   繁体   English

从python中的数组中提取值

[英]Extract values from array in python

I'm having some trouble accessing a value that is inside an array that contains a dictionary and another array.我在访问包含字典和另一个数组的数组中的值时遇到了一些问题。

It looks like this:它看起来像这样:

[{'name': 'Alex',
  'number_of_toys': [{'classification': 3, 'count': 383},
   {'classification': 1, 'count': 29},
   {'classification': 0, 'count': 61}],
  'total_toys': 473},
 {'name': 'John',
  'number_of_toys': [{'classification': 3, 'count': 8461},
   {'classification': 0, 'count': 3825},
   {'classification': 1, 'count': 1319}],
  'total_toys': 13605}]

I want to access the 'count' number for each 'classification'.我想访问每个“分类”的“计数”数字。 For example, for 'name' Alex, if 'classification' is 3, then the code returns the 'count' of 383, and so on for the other classifications and names.例如,对于 'name' Alex,如果 'classification' 为 3,则代码返回 383 的 'count',其他分类和名称依此类推。

Thanks for your help!谢谢你的帮助!

Not sure what your question asks, but if it's just a mapping exercise this will get you on the right track.不确定您的问题要问什么,但如果这只是一个映射练习,这将使您走上正确的轨道。

def get_toys(personDict):
    person_toys = personDict.get('number_of_toys')
    return [ (toys.get('classification'), toys.get('count')) for toys in person_toys]

def get_person_toys(database):
    return [(personDict.get('name'), get_toys(personDict)) for personDict in database]

This result is:这个结果是:

[('Alex', [(3, 383), (1, 29), (0, 61)]), ('John', [(3, 8461), (0, 3825), (1, 1319)])]

This isn't as elegant as the previous answer because it doesn't iterate over the values, but if you want to select specific elements, this is one way to do that:这不像之前的答案那么优雅,因为它不会迭代值,但是如果您想选择特定元素,这是一种方法:

data = [{'name': 'Alex',
  'number_of_toys': [{'classification': 3, 'count': 383},
   {'classification': 1, 'count': 29},
   {'classification': 0, 'count': 61}],
  'total_toys': 473},
 {'name': 'John',
  'number_of_toys': [{'classification': 3, 'count': 8461},
   {'classification': 0, 'count': 3825},
   {'classification': 1, 'count': 1319}],
  'total_toys': 13605}]    

import pandas as pd
df = pd.DataFrame(data)
print(df.loc[0]['name'])
print(df.loc[0][1][0]['classification'])
print(df.loc[0][1][0]['count'])

which gives:这使:

Alex
3
383

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM