检查两个列表之间的公共元素是否顺序相同

时间:2020-01-23 10:47:21

标签: python python-3.x list

例如,有三个列表:

list_1 = ["a","b","c","d"]
list_2 = ["a","x","b","y","c"]
list_3 = ["b","a","c"]
common_elements = ["a","b","c"]

现在我的要求是找出列表中是否包含相同的元素,它们是否以相同的顺序出现。

例如,在list_1中,常见元素的顺序为a,b,c,而在list_2中,常见元素的出现顺序也与list_1中的a,b,c相同

但是在list_3中,公共元素与list_1的顺序不同。

我们如何确定公共元素是否顺序相同?

3 个答案:

答案 0 :(得分:3)

目前尚不清楚是需要将三个列表同时使用还是仅将其中两个列表相交。这是任何两个列表的简单方法的说明:

function IsNull(ADate: TDateTime): Boolean;
begin
  Result := ADate = Default(TDateTime);
end;

答案 1 :(得分:0)

您可以通过简单地迭代一个列表并在第二个列表中搜索公用元素来做到这一点,但是从找到上一个元素的位置开始搜索。例如,如下所示:

def common_in_order(lst1, lst2):
    # Find common elements
    common = set(lst1)
    common.intersection_update(lst2)
    # Index of the last element found in lst2
    prev_idx = 0
    # Iterate elements of lst1
    for elem in lst1:
        # If it is a common element
        if elem in common:
            try:
                # Look for the element from the previous index onwards
                prev_idx = lst2.index(elem, prev_idx)
            except ValueError:
                # If the element could not be found they are not in the same order
                return False
    # If there were no errors then elements were in the same order
    return True

# Test
list_1 = ["a","b","c","d"]
list_2 = ["a","x","b","y","c"]
list_3 = ["b","a","c"]
print(common_in_order(list_1, list_2))
# True
print(common_in_order(list_1, list_3))
# False
print(common_in_order(list_2, list_3))
# False

答案 2 :(得分:0)

您可以尝试以下方法:

list_1 = ["a","b","c","d"]
list_2 = ["a","x","b","y","c"]
list_3 = ["b","a","c"]

common_elements = ["a","b","c"]

for ix, l in enumerate([list_1, list_2, list_3],1):
    correct_order = True
    if set(common_elements).issubset(set(l)):
        idx = l.index(common_elements[0])
        for i in common_elements[1:]:
            if l.index(i) < idx:
                correct_order = False
                break
        if correct_order: print(f'list {ix} is in correct order')
        else: print(f'list {ix} does not have correct order')
    else:
        print(f'list {ix} does not have all common elements')

输出:

list 1 is in correct order
list 2 is in correct order
list 3 does not have correct order