我有定义的函数,它从我的JSON字符串
中检索所需的值2部分问题:
def galPrice(commodity):
comPrice = [item['meanPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
print json.dumps(comPrice)
从上面的函数返回的值为我[378]
如何返回项目名称以及值[meanPrice : 378]
在此示例中,我尝试打印多个选定的值,例如meanPrice
,buyPrice
和sellPrice
所以输出会给我:
[meanPrice : 378],
[buyPrice : 224],
[sellPrice : 209]
我能弄明白的唯一方法就是做以下事情我不确定这是否是最有效的方法。
def galPrice(commodity):
meanPrice = [item['meanPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
buyPrice = [item['buyPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
sellPrice = [item['sellPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
print 'Mean Price:', meanPrice
print 'Buy Price:', buyPrice
print 'Sell Price:', sellPrice
JSON:
{"lastStarport":{"id":"3230614016","name":"Vries Installation","faction":"Independent","commodities":[{"id":"128049204","name":"Explosives","cost_min":300,"cost_max":456,"cost_mean":"378.00","homebuy":"60","homesell":"56","consumebuy":"4","baseCreationQty":368,"baseConsumptionQty":0,"capacity":3868,"buyPrice":224,"sellPrice":209,"meanPrice":378,"demandBracket":0,"stockBracket":2,"creationQty":3868,"consumptionQty":0,"targetStock":3868,"stock":2166,"demand":0,"rare_min_stock":"0","rare_max_stock":"0","market_id":null,"parent_id":null,"statusFlags":[],"categoryname":"Chemicals","volumescale":"1.1400"}]}}
答案 0 :(得分:0)
您也可以使用帮助函数
def get_commodity_data(commodity):
for item in data['lastStarport']['commodities']:
if item['name'] == commodity:
return item
return None
def galPrice(commodity):
comdata = get_commodity_data(commodity)
return {
'meanPrice': comdata['meanPrice'],
'buyPrice': comdata['buyPrice'],
'sellPrice': comdata['sellPrice'],
}
print galPrice('Explosives')
输出
{'sellPrice': 209, 'meanPrice': 378, 'buyPrice': 224}
我认为这段代码应该回答1)和2)。如果没有,请在下面发表评论,我将澄清。
如果您不想硬编码所需的值,则下面的内容更灵活
def galPrice(commodity, values):
comdata = get_commodity_data(commodity)
return dict(zip(values, [comdata[value] for value in values]))
print galPrice('Explosives', ['meanPrice', 'buyPrice', 'sellPrice'])
它提供与上面相同的输出。
鉴于具有相同名称的多种商品,以下将给出每种商品的数据列表
def galPrice(commodity, values):
comdata = filter(lambda i: i['name'] == commodity,
data['lastStarport']['commodities'])
return [dict(zip(values, [com[value] for value in values]))
for com in comdata]
注意:这不再需要辅助函数。它实用了内置的filter()
函数和lambda expression。
首先,列表将过滤为仅具有所需名称的项目。然后从所述项目中提取所需的值。
示例输出:
[{'sellPrice': 209, 'meanPrice': 378, 'buyPrice': 224},
{'sellPrice': 210, 'meanPrice': 378, 'buyPrice': 224}]
或者,如果您对列表理解语法非常熟悉:
def galPrice(commodity, values):
return [dict(zip(values, [com[value] for value in values if com['name'] == commodity]))
for com in data['lastStarport']['commodities']]
使用与上面相同的输出。