user1901671
user1901671

Reputation: 3

How do I pull certain values from a list of lists in python?

def get_monthly_averages(original_list):

    #print(original_list)
    daily_averages_list = [ ]
    for i in range (0, len(original_list)):  
        month_list = i[0][0:7]
        volume_str = i[5]
        #print(volume_str)
        adj_close_str = i[6]
        #print(adj_close_str)
        daily_averages_tuple = (month_list,volume_str,adj_close_str)
        daily_averages_list.append(daily_averages_tuple.split(','))
    return daily_averages_list

I have a list like

[
 ['2004-08-30', '105.28', '105.49', '102.01', '102.01', '2601000', '102.01'], 
 ['2004-08-27', '108.10', '108.62', '105.69', '106.15', '3109000', '106.15'], 
 ['2004-08-26', '104.95', '107.95', '104.66', '107.91', '3551000', '107.91'], 
 ['2004-08-25', '104.96', '108.00', '103.88', '106.00', '4598900', '106.00'], 
 ['2004-08-24', '111.24', '111.60', '103.57', '104.87', '7631300', '104.87'], 
 ['2004-08-23', '110.75', '113.48', '109.05', '109.40', '9137200', '109.40'], 
 ['2004-08-20', '101.01', '109.08', '100.50', '108.31', '11428600', '108.31'], 
 ['2004-08-19', '100.00', '104.06', '95.96', '100.34', '22351900', '100.34']
]

I am attempting to pull certain multiple values from within each list within the 'long' list. I need to use beginning python techniques. For instance, we haven't learned lambda in the class as of yet. MUST use beginning techniques.

as of right now the lines using i[][] are giving me a type error saying that 'int' is not subscriptable.

Upvotes: 1

Views: 232

Answers (3)

Marcin
Marcin

Reputation: 49816

Don't use range to iterate over lists. Do this:

for datestr, n1, n2, n3, someval, otherval in original_list:
    #do your stuff here

This will iterate over every list in original_list, and assign the 6 elements of each such list to the variables given.

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113930

I think you wwant

month_list = original_list[i][0][0:7]
volume_str = original_list[i][5]
#print(volume_str)
adj_close_str = original_list[i][6]

Upvotes: 0

Matt
Matt

Reputation: 3741

Your variable i is an integer. You should be indexing into original_list and not i.

Upvotes: 1

Related Questions