2015-04-02 97 views
2

給定索引列表,如何檢查列表列表中這些索引處的列表是否相同?檢查列表中某些索引處的重複列表

# 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 

回答

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 

順便說一句,謝謝你提供的輸入和預期輸出的明顯的例子。

+2

不能保證'0'在索引中,應該在索引中使用'all(lsts [indices] [0] == lsts [i])' – AChampion 2015-04-02 01:05:35