using any in python

Asked

Viewed 104 times

0

I have 2 lists with several fixed/mobile numbers. Example:

Lista 1: ['0169924233316','01687665544','01978553322']<br>
Lista 2:: ['0169924233316', '01788226541']<br>

Within a go, I compare the 2 lists to know if there is any repeated number, if there is not I put that number on a third list. Code:

if not any(lista1[0] in checkNumero for checkNumero in lista2): <br>
    lista3.append(lista1[0])

The problem is this. I now need to add another field that would be date-time, making the lists a list of dictionaries. Example:

Lista 1: [{'numero':'0169924233316', 'data':'2017-16-10'},{'numero':'01687665544', 'data':'2017-16-10'},{'numero':'01978553322', 'data':'2017-16-10'}]<br>
Lista 2:: [{'numero':'0169924233316', 'data':'2017-16-10'}, {'numero':'01788226541', 'data':'2017-16-10'}]


How would it be for me to use the 'any' function to compare both the number and the time of the dictionary?

2 answers

1


lista1 = [
    {'numero':'0169924233316', 'data':'2017-16-10'},
    {'numero':'01687665544', 'data':'2017-16-10'},
    {'numero':'01978553322', 'data':'2017-16-10'}]

lista2 = [{'numero':'0169924233316', 'data':'2017-16-10'}, 
        {'numero':'01788226541', 'data':'2017-16-10'}]

lista3 = []
for val in lista1:
    for val2 in lista2:
        if not any(val['numero']) in val2 and any(val['data']) in val2:
            lista3.append(
                {'numero':val['numero'],
                 'data':val['data']
                } 
            )

print(lista3)

1

You can convert your dictionary to a set in order to facilitate operations if subtraction between lists of dictionaries:

from datetime import date

l1 = ['0169924233316','01687665544','01978553322']
l2 = ['0169924233316', '01788226541']

# Converte listas para dicionarios incluindo a chave 'data'
dic1 = [ { 'numero' : k, 'data' : date.today().strftime("%Y-%d-%m") } for k in l1 ]
dic2 = [ { 'numero' : k, 'data' : date.today().strftime("%Y-%d-%m") } for k in l2 ]

# Converte dicionarios para sets
s1 = (frozenset(x.iteritems()) for x in dic1)
s2 = (frozenset(x.iteritems()) for x in dic2)

# Calcula diferenca entre os sets
s3 = set(s1).difference(s2)

# Converte set para dicionario
dic3 = [dict(x) for x in s3]

# Exibe dicionarios
print "Lista1: ",  dic1
print "Lista2: ",  dic2
print "Lista3: ",  dic3

Exit:

Lista1:  [{'data': '2017-16-10', 'numero': '0169924233316'}, {'data': '2017-16-10', 'numero': '01687665544'}, {'data': '2017-16-10', 'numero': '01978553322'}]
Lista2:  [{'data': '2017-16-10', 'numero': '0169924233316'}, {'data': '2017-16-10', 'numero': '01788226541'}]
Lista3:  [{'data': '2017-16-10', 'numero': '01978553322'}, {'data': '2017-16-10', 'numero': '01687665544'}]

Browser other questions tagged

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