python - Nest for loop not running after first iteration of outside loop -
i have program loads of list of stock tickers , sectors list called etfstocks. looks following:
etfstocks = [('aapl', 'technology'), ('fb', 'technology'), ('spg', 'real estate'), ...]
i have list have each sector loaded list called sectorlist. looks following:
sectorlist = ('technology', 'real estate', 'industrials', ...)
i'm trying iterate on sectorlist list , load each of tickers given sector own list, perform analysis on. script below works first pass, when loop goes second sector, never rebuilds sectorstock list. i've tried switching between code below , nest loops, nothing seems work.
does have idea why won't re-iterate on nested loop?
sectorstocks = [] sector in sectorlist: sectorstocks.clear() sectorstocks = [i[0] in etfstocks if i[1] == sector] print("computing statistics for: %s" % sector)
seems work here.
perhaps want groupby
?
from itertools import groupby operator import itemgetter etfstocks = [('aapl', 'technology'), ('fb', 'technology'), ('spg', 'real estate')] sectorlist = ('technology', 'real estate', 'industrials') stocks_by_sector = {k:list(v) k,v in groupby(etfstocks, itemgetter(1))} sector, stocks in stocks_by_sector.items(): print(sector, stocks)
Comments
Post a Comment