I want two lists. One list giving all tickers up for the day and one list giving me all the tickers down for the day.
Given:
stocks = [{'ticker':'IBM', 'open': 139.50, 'close': 125.32},
{'ticker':'NIO', 'open': 43.80, 'close': 40.30},
{'ticker':'WMT', 'open': 134.80, 'close': 130.23},
{'ticker':'GE', 'open': 10.13, 'close': 10.50}]
I have tried the following; and, it works; however, is there a better way?
stocks_down_list = [stocks[x]['ticker'] for x in range(len(stocks)) if stocks[x]['close'] -stocks[x]['open'] < 0]
stocks_up_list = [stocks[x]['ticker'] for x in range(len(stocks)) if stocks[x]['close'] - stocks[x]['open'] > 0]
CodePudding user response:
You can use the below code to only iterating through the stocks list once and more concise
for stock in stocks:
(stocks_up_list, stocks_down_list)[stock['close'] < stock['open']].append(stock)
CodePudding user response:
Which is a "better" way could certainly be left open to interpretation, however to reduce the time complexity you could definitely consider iterating over the list of stocks once, rather than twice to build each list
separately via a comprehension approach.
For example:
stocks = [{'ticker': 'IBM', 'open': 139.50, 'close': 125.32},
{'ticker': 'NIO', 'open': 43.80, 'close': 40.30},
{'ticker': 'WMT', 'open': 134.80, 'close': 130.23},
{'ticker': 'GE', 'open': 10.13, 'close': 10.50}]
stocks_up_list = []
stocks_down_list = []
for stock in stocks:
ticker = stock['ticker']
if stock['close'] >= stock['open']:
stocks_up_list.append(ticker)
else:
stocks_down_list.append(ticker)