2016-01-09 110 views
1

我正在使用Google财务模块来获取Python中的库存数据。我想从列表中分离出LastTradePrice并将其转换为整数。有什么建议么?谢谢。在Python列表中分离字符串

from googlefinance import getQuotes 
import json 

stockinfo = getQuotes('VSMGX') 

stockdata = json.dumps(stockinfo, indent=1) 

的stockdata看起来像这样

[ 
{ 
    "ID": "904726512134516", 
    "LastTradeDateTimeLong": "Jan 8, 4:00PM EST", 
    "Index": "MUTF", 
    "LastTradeWithCurrency": "$22.26", 
    "LastTradeTime": "4:00PM EST", 
    "StockSymbol": "VSMGX", 
    "LastTradePrice": "22.26", 
    "LastTradeDateTime": "2016-01-08T16:00:00Z" 
} 
] 
+2

你真的想要它是一个整数? '22.26'会回到'22'。 '[float(d ['LastTradePrice'])对于股票数据中的任何错误''。 BTW'info1'不存在 - 你的意思是'stockinfo'吗? – AChampion

+0

是的,我应该使用浮动。谢谢!你的回答起作用 –

+0

糟糕,我只是写了与@AChampion相同的代码,令牌令牌!那么它是一个成语:-) – alexis

回答

0

其实,你想有一个浮动,因为lastTradePrice有小数。迭代列表并提取最近交易价格的关键字的字典值。

lastTradedPrices = [] 
for data in stockdata: 
    lastTradedPrices.append(float(data["LastTradePrice"])) 
1

如果所有的记录有最后交易价格,只是用一个列表理解:

tradePrices = [ float(d["LastTradePrice"]) for d in stockdata ] 

编辑:将其转换为float为@mattsap建议。发现得好!