Hey all,

Here is what I'm trying to do. I have a list whose output is:

[['4/18/94', '29.125', '442.46'], ['4/19/94', '29.336', '442.54'], ['1/20/04', '75.175', '1138.77'], ['1/21/04', '75.711', '1147.62'], ['1/22/04', '75.595', '1143.94']]

Item [1] in each list, the middle item, is the number I want to focus on. Currently, I have my sentiment range set between 30 and 75. These are sentiment numbers in item[1] of each list within the larger list.

I want to make it so that no 2 item[1]'s are below 30 in a row, and no 2 item[1]'s are above 75 in a row.

So looking only at the sentiment numbers, here is how I want my list ordered:

[['4/18/94', '29.125', '442.46'], ['1/20/04', '75.175', '1138.77']]

That's a simple version. But basically for every list within a list that has a sentiment number below 30, the next list within the list should have a sentiment number above 75.

for x in range(1,len(list_of_sentiments)):
    if float(list_of_sentiments[x][1]) < Low_Sentiment:
        if float(list_of_sentiments[x-1][1]) < Low_Sentiment:
            del list_of_sentiments[x]
print list_of_sentiments

I keep getting an index range error because of the x-1. I get the same error when i try to switch it around with an x+1. Is there any easier way to get rid of the lists with sentiment numbers in the same range as the item before?

9 Years
Discussion Span
Last Post by rasizzle

Got it :D

data = [['4/18/94', '29.125', '442.46'],
    ['4/19/94', '29.336', '442.54'],
    ['1/20/04', '75.175', '1138.77'],
    ['1/21/04', '75.711', '1147.62'],
    ['1/22/04', '75.595', '1143.94']]
result = []

for item in data:
    # current middle index as a float
    n = float(item[1])
    # if there are no items in the result list yet
    if not result:
    # otherwise, if there are,
        # previous number (last one in result list) as a float
        prevnum = float(result[-1][1])
        if (prevnum < 30 and n > 75) or (prevnum > 75 and n < 30):

My result:
[['4/18/94', '29.125', '442.46'], ['1/20/04', '75.175', '1138.77']]
Votes + Comments
excellent advice

Yes! That works perfectly. Thanks for coming through again. If you haven't guessed, I still haven't been able to fully use my Buy and Sell program. I am re-attempting to find a simpler way to do it and this looks great. Thanks again!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.