Remove elements from a Python Parameter List

0

Basically I want to remove elements from a secondary list based on the result of another list. I have two lists:

lista_8 = ['', '', 'Preco', '', 'Preco', '', '', 'Preco']

lista_n = ['positivo', 'positivo', 'negativo', 'positivo', 'negativo', 'positivo', 'positivo', 'negativo']

Follow logic:

When the element of lista_8 is empty, the element of lista_n is also empty, otherwise it keeps the result (positive or negative).

My code looks like this:

for w in lista_8:
    if lista_8[w] == 0:
        lista_n[w+1] = 0

print lista(n)

The following error occurs:

if_list_8 [w] == 0:

TypeError: list indices must be integers or slices, not str

    
asked by anonymous 31.10.2018 / 18:39

3 answers

3

Using enumerate you can number a list making it easy to work with.

lista_8 = ['', '', 'Preco', '', 'Preco', '', '', 'Preco']
lista_n = ['positivo', 'positivo', 'negativo', 'positivo', 'negativo', 'positivo', 'positivo', 'negativo']

for w, value in enumerate(lista_8, 0):
    #if lista_8[w] == '': funciona desta maneira também
    if value == '':
        lista_n[w] = ''

print("lista_8\n")
print(lista_8)
print("\nlista_n\n")
print(lista_n)

Executing the code: link

    
31.10.2018 / 18:58
2

Python has the itertools function in the compress package . , which removes from an iterable object the values according to the value of another iterable value.

def compress(data, selectors):
    # compress('ABCDEF', [1,0,1,0,1,1]) --> 'A' 'C' 'E' 'F'
    return (d for d, s in zip(data, selectors) if s)

That is, for:

A = ['', '', 'Preco', '', 'Preco', '', '', 'Preco']
B = ['positivo', 'positivo', 'negativo', 'positivo', 'negativo', 'positivo', 'positivo', 'negativo']

When doing compress(B, A) the result would be ['negativo', 'negativo', 'negativo'] , but that's not exactly what we want. We can then adapt this function by creating a compress_with_replacement that, instead of removing the element, replaces it with a defined value:

def compress_with_replacement(data, selectors, replace=''):
    # compress_with_replacement('ABCDEF', [1,0,1,0,1,1], '') --> 'A' '' 'C' '' 'E' 'F'
    return (d if s else replace for d, s in zip(data, selectors))

So, the return of compress_with_replacement(B, A) will be:

['', '', 'negativo', '', 'negativo', '', '', 'negativo']

Note: Return is actually a generator. The above result was obtained by converting the generator to a list.

    
31.10.2018 / 19:11
0

It worked for the enumerate and so also, below:

i_temp = -1
for w in lista_8:
    i_temp = i_temp + 1
    if len(w) == 0:
        lista_n[i_temp] = 0
print(lista_8)
print(lista_n)
    
31.10.2018 / 20:00