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?

Dani AI

Generated

The IndexError you hit comes from mutating the list while iterating over an index range computed up front: removing items shortens the list and later indices go past the new end. Building a new list avoids that class of bug — which is why ’s append-into-result approach works reliably.

Two alternative, safe patterns:

  • In-place deletion but iterate backwards. Walking indices from the end to the start avoids shifting problems because removing data[i] does not affect indices you have yet to visit:

    for i in range(len(data)-1, 0, -1):
        curr = float(data[i][1])
        prev = float(data[i-1][1])
        if curr < LOW and prev < LOW:
            del data[i]
        elif curr > HIGH and prev > HIGH:
            del data[i]
  • Collapse consecutive runs with itertools.groupby and keep one representative per run (useful if you want to compress long runs of lows or highs to a single entry):

    from itertools import groupby
    
    def category(item):
        n = float(item[1])
        return 'L' if n < LOW else 'H' if n > HIGH else 'M'
    
    collapsed = []
    for key, group in groupby(data, key=category):
        if key in ('L', 'H'):
            collapsed.append(next(group))   # keep first of each low/high run
        else:
            collapsed.extend(list(group))   # keep mids as-is (adjust as desired)

Small practical notes: decide how to treat boundary values (30 and 75) — use </<= consistently. Convert the middle-item strings to floats once up front to avoid repeated conversions and potential ValueError on malformed input. For very large streams prefer a generator-based approach so you don’t hold two full copies in memory. Finally, add a few unit tests that cover runs (LLL, HHH), alternating extremes (L,H,L), and mixed mids to confirm the behavior matches expectations.

Recommended Answers

All 2 Replies

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.