将列表的一半大小移动到其他列表以获取公共元素

时间:2014-12-16 19:15:00

标签: python pandas

我有两个列表s1s2。我需要在左边滑动第二个列表的一半大小并返回第一个列表中的匹配元素。然后我需要将第二个列表移动一个位置并获取公共元素,如下面的Answer所示。我正在计划对返回的每对子列表执行一些操作。实现这一目标的好方法是什么。

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 

答案:

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 

2 个答案:

答案 0 :(得分:2)

希望你明白这个想法

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

答案 1 :(得分:2)

它没有进行任何边界检查,但这应该可以解决问题:

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]

或者,如果您更喜欢某些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:]))

这是一个测试:

>>> 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])]

请注意,这会以相反的顺序生成对。