如何让这个代码更加Pythonic - 特别是将某些东西合并到一个函数中?

时间:2015-09-22 17:52:03

标签: python python-3.x

我知道这个代码看起来会好很多,如果我这样做,那么检查当前价格与开放价格是一个函数,所以我不必为我想要的每一个股票重新编写它检查,但我不确定如何正确地开始这样做。你们中的任何人都有一些提示让我开始吗?

from yahoo_finance import Share

apple = Share('AAPL')

appleopen = float(apple.get_open())
applecurrent = float(apple.get_price())

if appleopen > applecurrent:
    print(("Apple is down for the day. Current price is"), applecurrent)
else:
    print(("Apple is up for the day! Current price is "), applecurrent)

applechange = (applecurrent - appleopen)
if applechange > 0:
    print(('The price moved'),abs(applechange),("to the upside today."))
else:
    print(('The priced moved'),abs(applechange),("to the downside today."))
print('-----------------------')
nflx = Share('NFLX')

nflxopen = float(nflx.get_open())
nflxcurrent = float(nflx.get_price())

if nflxopen > nflxcurrent:
    print(("Netflix is down for the day. Current price is"), nflxcurrent)
else:
    print(("Netflix is up for the day! Current price is "), nflxcurrent)

nflxchange = (nflxcurrent - nflxopen)
if nflxchange > 0:
    print(('The price moved'),abs(nflxchange),("to the upside today."))
else:
    print(('The priced moved'),abs(nflxchange),("to the downside today."))

1 个答案:

答案 0 :(得分:2)

试试这个:

from yahoo_finance import Share
Store = {
    'AAPL': 'Apple',
    'NFLX': 'Netflix'
}
for code in Store:
    name, shr = Store[code], Share(code)
    sopen = float( shr.get_open() )
    scurr = float( shr.get_price() )
    schange = scurr - sopen
    movement = 'down' if schange < 0 else 'up'
    print( format("{} is {} for the day. Current price is {}"), name, movement, scurr) )
    print( format('The price moved {} to the {}side today.',abs(schange), movement) )
    print('-----------------------')