I have two lists s1
and s2
. I need to slide the second list half its size on left and return the matching elements in first list. Then I need to move the second list one position and get the common elements as shown in the Answer
below. I am plaaning to perforn some operation on each pair of sublists returned. What is the good way to accomplish this.
s1 = [11, 12, 13, 14, 15, 16, 17, 18]
s2 = [21, 22, 23, 24, 25, 25]
11 12 13 14 15 16 17 18
21 22 23 24 25 25
Answer:
11 12 13
24 25 25
11 12 13 14
23 24 25 25
11 12 13 14 15
22 23 24 25 25
11 12 13 14 15 16
21 22 23 24 25 25
12 13 14 15 16 17
21 22 23 24 25 25
13 14 15 16 17 18
21 22 23 24 25 25
14 15 16 17 18
21 22 23 24 25
15 16 17 18
21 22 23 24
16 17 18
21 22 23
Hope you get the idea
s1 = [11, 12, 13, 14, 15, 16, 17, 18]
s2 = [21, 22, 23, 24, 25, 25]
l1 = len(s1)
l2 = len(s2)
l = min(l1,l2)+1
k = l2/2;
for i in range(k,l2+1):
print s1[:i]
print s2[-i:]
print
for i in range(1,l1-l2):
print s1[i:i+l2]
print s2[:]
print
for i in reversed(range(k,l)):
print s1[-i:]
print s2[:i]
print
It doesn't do any bounds-checking, but this should do the trick:
def slide(s1, s2, size):
start = size - len(s1)
finish = len(s2) - size + 1
for offset in xrange(start, finish):
m = max(-offset, 0)
n = max( offset, 0)
l = min(len(s1) - m, len(s2) - n)
yield s1[m:m+l], s2[n:n+l]
Or, if you'd prefer some zip
trickery:
def slide(s1, s2, size):
start = size - len(s1)
finish = len(s2) - size + 1
for offset in xrange(start, finish):
m = max(-offset, 0)
n = max( offset, 0)
yield zip(*zip(s1[m:], s2[n:]))
Here's a test:
>>> s1 = [11, 12, 13, 14, 15, 16, 17, 18]
>>> s2 = [21, 22, 23, 24, 25, 25]
>>> list(slide(s1, s2, 3))
[([16, 17, 18], [21, 22, 23]),
([15, 16, 17, 18], [21, 22, 23, 24]),
([14, 15, 16, 17, 18], [21, 22, 23, 24, 25]),
([13, 14, 15, 16, 17, 18], [21, 22, 23, 24, 25, 25]),
([12, 13, 14, 15, 16, 17], [21, 22, 23, 24, 25, 25]),
([11, 12, 13, 14, 15, 16], [21, 22, 23, 24, 25, 25]),
([11, 12, 13, 14, 15], [22, 23, 24, 25, 25]),
([11, 12, 13, 14], [23, 24, 25, 25]),
([11, 12, 13], [24, 25, 25])]
Note that this produces the pairs in reverse order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.