Search for tuple in an array

4

I have the following vectors:

a = [('FI', 'SE'), ('SE', 'DK'), ('DK', 'DE'), ('DE', 'PL'), ('PL', 'BY')]

b = [['NL', 'DK', 0], ['NL', 'DE', 0], ['NL', 'BE', 0], ['FI', 'SE', 0.054]]

I need to go through the a vector and find it in the vector b .

My output has to return:

c = ['FI', 'SE', 0.054]

How can I do this?

Thanks for the help.

    
asked by anonymous 02.05.2018 / 20:00

3 answers

2

You can try this:

a = [('FI', 'SE'), ('SE', 'DK'), ('DK', 'DE'), ('DE', 'PL'), ('PL', 'BY')]
b = [['NL', 'DK', 0], ['NL', 'DE', 0], ['NL', 'BE', 0], ['FI', 'SE', 0.054]]

search1, search2 = ('FI', 'SE')
for val1, val2, val3 in b:
  if((val1, val2) == (search1, search2)):
    print(val1, val2, val3) # FI SE 0.054
    break
else: # caso nao haja break e porque nao foi encontrado
  print('não foi encontrado')

STATEMENT

If you want to find all elements of a in b , you can:

a = [('FI', 'SE'), ('SE', 'DK'), ('DK', 'DE'), ('DE', 'PL'), ('PL', 'BY')]
b = [['NL', 'DK', 0], ['NL', 'DE', 0], ['NL', 'BE', 0], ['DE', 'PL', 0], ['FI', 'SE', 0.054]]

founds = []
for val1, val2, val3 in b:
  if((val1, val2) in a):
   founds.append([val1, val2, val3])
print(founds) # [['DE', 'PL', 0], ['FI', 'SE', 0.054]]

STATEMENT

Or:

a = [('FI', 'SE'), ('SE', 'DK'), ('DK', 'DE'), ('DE', 'PL'), ('PL', 'BY')]
b = [['NL', 'DK', 0], ['NL', 'DE', 0], ['NL', 'BE', 0], ['DE', 'PL', 0], ['FI', 'SE', 0.054]]

founds = [[v[0], v[1], v[2]] for v in b if (v[0], v[1]) in a]
print(founds) # [['DE', 'PL', 0], ['FI', 'SE', 0.054]]
    
02.05.2018 / 20:17
2

If, instead of a list of lists, you can load b as a dictionary (or transform b into a bd dictionary, as I did in the example below) the code can be more intuitive, bd.get to find the required value. Ex.:

a = [('FI', 'SE'), ('SE', 'DK'), ('DK', 'DE'), ('DE', 'PL'), ('PL', 'BY')]
b = [['NL', 'DK', 0], ['NL', 'DE', 0], ['NL', 'BE', 0], ['FI', 'SE', 0.054]]

bd = dict(((x, y), z) for x, y, z in b)
print(bd)
# saída: {('FI', 'SE'): 0.054, ('NL', 'BE'): 0, ('NL', 'DE'): 0, ('NL', 'DK'): 0}

c = [(i, bd.get(i)) for i in a if i in bd]    
print(c)
# saída: [(('FI', 'SE'), 0.054)]
    
03.05.2018 / 01:51
1

See if this helps you:

a = [('FI', 'SE'), ('SE', 'DK'), ('DK', 'DE'), ('DE', 'PL'), ('PL', 'BY')]

b = [['NL', 'DK', 0], ['NL', 'DE', 0], ['NL', 'BE', 0], ['FI', 'SE', 0.054]]

result = []
for x in a:
    for z in b:
        if len(list(set(x) - set(z))) == 0:
            result.append(z)

print(result) # [['FI', 'SE', 0.054]]

In the example I go through the 2 lists and check the difference between the elements to get the result you expect, and then add it to the result list.

NOTE: I'm starting the studies in python, so sorry for anything.

    
02.05.2018 / 20:20