Python-检查两个有序列表中的公共元素及其邻居

时间:2017-09-19 14:27:23

标签: python list

对于两个给定的有序列表(它们可以是不同的大小):

old_state = [1, 2, 4, 5]
new_state = [1, 3, 2, 5]

如何找到共同元素并根据其邻居的变化(以尽可能最快的方式)对元素进行分类?

例如,对于上面的列表,常见元素是(1,2,5),它们的分类如下:

1 的右邻居已从 2 更改为 3

RN = [1]

2 的两个邻居已更改(左邻居:1 - > 3,右邻居:4 - > 5)

RLN = [2]

最后左边的第5项已从 4更改为

LN = [5]

我知道找到共同元素的最好方法是使用set()但是当找到邻居时我会被卡住。

1 个答案:

答案 0 :(得分:0)

也许这可以满足您的需求:

old_state = [1, 2, 4, 5]
new_state = [1, 3, 2, 5]

RN = []
LN = []
RLN = []

# We iterate through the common elements
common_elements = list(set(old_state).intersection(new_state))
for elem in common_elements:
    # We retrieve the neighbors on both sides
    # First in the old state
    old_index = old_state.index(elem)
    old_state_left = Flase  # Placeholder in case it has no left neighbor
    old_state_right = Flase  # Placeholder in case it has no right neighbor
    if old_index != 0:
        old_state_left = old_state[old_index-1]
    if old_index != len(old_state)-1:
        old_state_right = old_state[old_index+1]

    # Then in the new state
    new_index = new_state.index(elem)
    new_state_left = Flase  # Placeholder in case it has no left neighbor
    new_state_right = Flase  # Placeholder in case it has no right neighbor
    if new_index != 0:
        new_state_left = new_state[new_index-1]
    if new_index != len(new_state)-1:
        new_state_right = new_state[new_index+1]

    # Now we check in which list the element should be
    if new_state_left != old_state_left:
        # Could be LN or RLN
        if new_state_right != old_state_right:
            # Is RLN
            RLN.append(elem)
        else:
            # Is LN
            LN.append(elem)
    elif new_state_right != old_state_right:
        # Is RN
        RN.append(elem)

print(RN)  # outputs [1]
print(RLN)  # outputs [2]
print(LN)  # outputs [5]