Remove list duplicity with Python

Asked

Viewed 39 times

-1

I need to remove objects that have the same conta, saldo_devedor, and that the limite be equal to 0.

list = [
          {
            'conta': u'1.3.02', 
            'saldo_devedor': 999.08, 
            'limite': 2500.0
          }, 
          { 'conta': u'1.3.02', 
            'saldo_devedor': 999.08, 
            'limite': 0.0
          },
          { 'conta': u'1.3.03', 
            'saldo_devedor': 600.00, 
            'limite': 1000.00
          }
        ]

In this case there are 2 records that have the same conta and saldo_devedor, but the one that has the limite equal to 0 has to be removed, thus leaving the list:

list = [
          {
            'conta': u'1.3.02', 
            'saldo_devedor': 999.08, 
            'limite': 2500.0
          },
          { 'conta': u'1.3.03', 
            'saldo_devedor': 600.00, 
            'limite': 1000.00
          }
        ]

I tried an example I saw, but the error and I don’t know if that’s the way you can do it:

new_list = list(filter(lambda x, y: x.conta == y.conta and x.saldo_devedor == y.saldo_devedor and x.limit != 0, list_1))

Error:

Traceback (most recent call last):
  File "main.py", line 18, in <module>
    new_list = list(filter(lambda x, y: x.conta == y.conta and x.saldo_devedor == y.saldo_devedor and x.limit != 0, list_1))
TypeError: <lambda>() missing 1 required positional argument: 'y'
  • 1

    What problem presented with your code?

  • I’m new to Python, so I don’t know how to do it, new_list = filter(lambda x, y: x.conta == y.conta and x.saldo_devedor == y.saldo_devedor and x.limit == 0, list_1), I tried that there, but it didn’t work.

  • Would do using for (instead of using filter and lambda)?

  • Use a for even to solve, but I wonder if you have a better solution.

2 answers

0


I found a solution:

[x for x in consulta_limite if not ([y['conta'] for y in consulta_limite].count(x['conta']) > 1 and not [z['saldo_devedor'] for z in consulta_limite].count(x['saldo_devedor']) == 0 and x['limite'] == 0.0)]

This guy returns me already the filtered list

0

I did a job but simple to understand. It receives by parameter your list and the indexes you want to compare, which in this case is the first and the second. The function deletes duplicate data confirm you have set.

# Recebe lista, indice1, indice 2
def remove_duplicada(lista, x, y):
    if lista[x]["conta"] == lista[y]["conta"] and lista[x]["saldo_devedor"] == lista[y]["saldo_devedor"]:
        if lista[x]["limite"] == 0.0:
            del lista[x]
        else:
            del lista[y]

remove_duplicada(lista, 1, 0)
print(lista)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.