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

2024-04-24 01:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我如何根据最快的方法找到它们的共同元素?在

例如,对于上述列表,常见元素为(1、2、5),其分类为:

项目1的右邻域已从2变为3

^{pr2}$

项目2的两个邻居都发生了变化(左邻居:1->;3,右邻居:4->;5):

RLN = [2]

最后,第5项的左邻域从4变为2

LN = [5]

我知道找到公共元素的最好方法是使用set(),但在查找相邻元素时,我就卡住了。在


Tags: 项目方法gt元素列表new分类old
1条回答
网友
1楼 · 发布于 2024-04-24 01:12:31

也许这能满足你的需要:

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]

相关问题 更多 >