[英]Moving a list half its size against other list to get the common elements
I have two lists s1
and s2
. 我有两个列表
s1
和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. 然后,我需要将第二个列表移动一个位置,并获得公共元素,如下面的
Answer
所示。 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: 或者,如果您更喜欢一些
zip
骗术:
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. 请注意,这会产生相反的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.