Home > Software engineering >  How to compare lists in python in subgroups
How to compare lists in python in subgroups

Time:10-18

I'm now in python so any help or recomendation is appreciated.

What I'm trying to do is, having two lists (not necessarily inverted).

For instance:

l1 = [1,2,3,4,5]
l2 = [5,4,3,2,1]

Comparing them to return the common values, but not as anyone would normally do, which in this case, the return will be all the elements of the list, because they are the same, just inverted. What I'm trying to compare is, the same thing but like in stages, or semi portions of the list, and check if there is any coincidence until there, if it is, return that element, if not, keep looking in the next group.

For instance: the first iteration, would check (having the lists previously defined:

l1 = [1]
l2 = [5]
#is there any coincidence until there? -> false (keep looking)

2nd iteration:

l1 = [1, 2]
l2 = [5, 4]
#is there any coincidence until there? -> false (keep looking)

3rd iteration:

l1 = [1, 2, 3]
l2 = [5, 4, 3]
#is there any coincidence until there? -> true (returns 3, which is the element where the coincidence was found)

All of this for needing to implementate the bidirectional search, but I'm finding myself currently stuck in this step as I'm not so used to the for loops and list handling yet.

CodePudding user response:

you can compare the elements of the two lists in the same loop:

l1 = [1,2,3,4,5]
l2 = [5,4,3,2,1]
 
for i, j in zip(l1, l2):
  if i == j:
    print('true')
  else:
    print('false')

CodePudding user response:

It looks like you're really asking: What is (the index of) the first element that l1 and l2 have in common at the same index?

The solution:

next((i, a) for i, (a, b) in enumerate(zip(l1, l2)) if a == b)

How this works:

  • zip(l1, l2) pairs up elements from l1 and l2, generating tuples
  • enumerate() gets those tuples, and keeps track of the index, i.e. (0, (1, 5), (1, (2, 4)), etc.
  • for i, (a, b) in .. generates those pairs of indices and value tuples
  • The if a == b ensures that only those indices and values where the values match are yielded
  • next() gets the next element from an iterable, you're interested in the first element that matches the condition, so that's what next() gets you here.

The working example:

l1 = [1, 2, 3, 4, 5]
l2 = [5, 4, 3, 2, 1]

i, v = next((i, a) for i, (a, b) in enumerate(zip(l1, l2)) if a == b)

print(f'index: {i}, value: {v}')  # prints "index: 2, value: 3"

CodePudding user response:

Another solution, using any() := operator:

l1 = [1, 2, 3, 4, 5]
l2 = [5, 4, 3, 2, 1]

if any((val := a) == b for a, b in zip(l1, l2)):
    print("There is common value =", val)
else:
    print("There isn't common value")

Prints:

There is common value = 3
  • Related