检查列表列表中某些索引的重复列表

时间:2015-04-02 00:51:52

标签: python python-3.x

鉴于索引列表,我如何检查列表列表中这些索引的列表是否相同?

# Given:
# indices = [0, 2, 3]
# lsts = [['A', 'B'], ['1', '2', '3'], ['A', 'B'], ['B', 'C']]
# would test if ['A', 'B'] == ['A', 'B'] == ['B', 'C']
# would return False

# Given:
# indices = [0, 2]
# lsts = [['A', 'B'], ['1', '2', '3'], ['A', 'B'], ['B', 'C']]
# would test ['A', 'B'] == ['A', 'B']
# would return True

我目前有:

for i in range(len(lsts)):
    for i in range(len(indices) - 1):
        if lsts[indices[i]] != lsts[indices[i + 1]]:
            return False
    else:
        return True

1 个答案:

答案 0 :(得分:7)

这应该这样做:

>>> indices = [0, 2, 3]
>>> lsts = [['A', 'B'], ['1', '2', '3'], ['A', 'B'], ['B', 'C']]
>>> all(lsts[indices[0]] == lsts[i] for i in indices)
False
>>> indices = [0, 2]
>>> lsts = [['A', 'B'], ['1', '2', '3'], ['A', 'B'], ['B', 'C']]
>>> all(lsts[indices[0]] == lsts[i] for i in indices)
True

顺便说一句,感谢您提供输入和预期输出的明确示例。