初学Python程序员,需要帮助缩短代码

时间:2016-11-27 09:16:28

标签: python python-2.7

使用名为“nsetools”的第三方库获取库存数据

from nsetools import Nse
nse = Nse()

stocks = {
    "ADANIPORTS" : 284.95,
    "HINDALCO"   : 152.30,
    "ONGC"       : 279.70,
    "SBIN"       : 259.70
}

qty = {
    "ADANIPORTS" : 20,
    "HINDALCO"   : 20,
    "ONGC"       : 20,
    "SBIN"       : 20
}

我想让代码从这里开始简短

### Adaniports
stock1      = nse.get_quote('adaniports')
stock1Close = stock1['closePrice']

### Hindalco
stock2      = nse.get_quote('hindalco')
stock2Close = stock2['closePrice']

### ONGC
stock3      = nse.get_quote('ongc')
stock3Close = stock3['closePrice']

### SBIN
stock4      = nse.get_quote('sbin')
stock4Close = stock4['closePrice']

current_value = (stock1Close * qty['ADANIPORTS']) + (stock2Close * qty['HINDALCO']) + (stock3Close * qty['ONGC']) + (stock4Close * qty['SBIN'])

有没有办法循环通过字典,访问每个股票的收盘价,然后最好用一两行计算投资的当前价值?

2 个答案:

答案 0 :(得分:0)

我在codereview.stackexchange.com上问了这个并得到了答案

def get_closing(stock):
    return nse.get_quote(stock)['closePrice']

stock_gen = (get_closing(stock) * qty for stock, qty in stock_qty.items())
current_value = sum(stock_gen) 

答案 1 :(得分:-1)

要做到这一点,你可以总结列表理解,[expression for var in collection]docs

中的参考部分5.1.3
current_value = sum([nse.get_quote(n.lower())['closePrice'] * qty[n] for n in qty.keys()])