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?

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:
        result.append(item)
        
    # otherwise, if there are,
    else:
        # 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):
            result.append(item)

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

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.