【问题标题】:How to check that first n elements of a list match a reference list in python 3.x?如何检查列表的前 n 个元素是否与 python 3.x 中的参考列表匹配?
【发布时间】:2020-10-12 09:00:27
【问题描述】:

在 Python 3.x 中比较一个列表和另一个列表的最有效方法是什么,确保前 n 个元素与另一个列表中的对应项匹配?参考列表将是静态的,但要比较的列表可能具有不同数量的元素。

list_reference = ['Apples','Bananas','Coconuts','grapefruits','limes']

# This would be valid (elements at index 0,1,2 match their counterpart in list 'list_reference')
list_1 = ['Apples','Bananas','Coconuts']

# This would be invalid (same number of elements but order is different)
list_2 = ['Apples','Coconuts','Bananas']

# This would be invalid (order is ok but list don't start with same element as 'list_reference'
list_3 = [ 'Bananas','Coconuts','grapefruits','limes']

【问题讨论】:

  • list_reference[:len(list_1)] == list_1?

标签: python list comparison


【解决方案1】:

您可以将allzip 一起使用:

all(x == y for x, y in zip(list_x, list_reference))

all 将在遇到错误元素时停止迭代,因此除了第一个错误元素之外不会执行任何多余的比较。

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2019-05-24
    • 2015-10-03
    • 2020-05-18
    • 1970-01-01
    • 2012-04-03
    • 2013-03-11
    • 1970-01-01
    • 2015-12-24
    相关资源
    最近更新 更多