Attach two lists of offsets ("zip offset"?)

Consider two lists, for example:

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
M = [1, 2, 3, 4, 5, 6, 7, 8]

For example, we are given a pair of elements that must be the same - for example, (d, 6). Is it possible to "align" lists with these elements, and then join the lists that still have elements in both lists, for example, as a crossroad between zip and the inner join?

This is probably best illustrated by an example. Using Land Mas stated above:

  • (d, 6) will result in [(a, 3), (b, 4), (c, 5), (d, 6), (e, 7), (f, 8)]
  • (h, 2) will result in [(g, 1), (h, 2)]
  • (a, 8) will result in [(a, 8)]

My context: I'm currently trying to create a neural network that can learn how to play chess by reading chess notations. This question is related to checking the diagonals on the board in order to update the position of the position. For example, if a white bishop just moved to b7 (one square from the lower right corner of the board), then it should appear from a square on the long diagonal h1-a8 or from a square on a6-c8 a short diagonal.

So, in my case L, Mthey have the same length, since they correspond to the ranks and files on the chessboard 8 by 8. But in general, I believe that lists can have different lengths.

+4
source share
2 answers

You can do something in the lines

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
M = [1, 2, 3, 4, 5, 6, 7, 8]
m = L.index('h')
n = M.index(2)
if m > n:
  m, n = (m - n), 0
else:
  m, n = 0, (n - m)
print(list(zip(L[m:], M[n:])))

PS , , m, n , , .

+1

, itertools.dropwhile , .

, iterables itertools.islice:

from itertools import dropwhile, islice, chain

def func(x, y, lst1, lst2):
    f1 = lambda i: i!=x
    f2 = lambda i: i!=y
    r =  zip(dropwhile(f1, lst1), dropwhile(f2, lst2))
    q  = reversed(zip(dropwhile(f1, reversed(lst1)), dropwhile(f2, reversed(lst2))))
    return list(chain(q, islice(r, 1, None)))

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
M = [1, 2, 3, 4, 5, 6, 7, 8]

print(func('d', 6, L, M))
# [('a', 3), ('b', 4), ('c', 5), ('d', 6), ('e', 7), ('f', 8)]

print(func('h', 2, L, M))
# [('g', 1), ('h', 2)]

print(func('a', 8, L, M))
# [('a', 8)]

, .

+1

Source: https://habr.com/ru/post/1681767/


All Articles