2013-11-25 114 views
1

我需要检查清单,清单包含到指定列表类似值列表,值可在不同的顺序,但如果所有的值都是相同的,它应该返回真列表与另一个列表列表比较

a= ["1","2","3","4","5"] 

b= ["2","3","6","4","7"] 

e = (["1","3","2","4","5"],["2","3","6","4","7"]) 


CombinationFound = [] 
for i in e: 
    if i == a: 
     CombinationFound = True 
     break; 
    else: 
     CombinationFound = False 

因为["1","2","3","4","5"]它应该返回true和["1","3","2","4","5"]有相同的价值观

+1

为什么'CombinationFound'列表? – Bryan

+0

你可以用'if if in a:'来检查项目'i'是否在'a'列表中。 – 2015-05-10 11:21:49

回答

0

尝试这些列表转换成集:

def isthesame(a,b): 
    return set(b) == set(a) 

例如,如果您有:

a= ["1","2","3","4","5"] 
b= ["2","3","6","4","7"] 

这个解决方案应该没有duplicit项目清单的工作。

+1

'isthesame(“猫”,“cart”)'返回'真'。那是故意的吗? – Kevin

+0

@Kevin你没有比较两个列表,但两个字符串。尝试使用'isthesame([“cat”],[“cart”])' – nio

+1

'isthesame([1,2,3],[1,2,3,4,5])''怎么样,它也返回TRUE;? – Kevin

0

您需要将您尝试匹配的列表转换为可以比较的对象,而不必关心原始顺序。如果列表元素的出现次数计数,则使用排序列表。如果没有,请使用套件。

list_to_match = sorted(a) 
combination_found = False 
for i in e: 
    if sorted(i) == list_to_match: 
     combination_found = True 
     break 

该版本将区分不同数量的重复元素的列表 - 也就是说,[0, 1, 1, 2]将不匹配[0, 1, 1, 1, 2]。如果你不关心这种可能性,使用set(a)set(i)代替:

set_to_match = set(a) 
combination_found = False 
for i in e: 
    if set(i) == set_to_match: 
     combination_found = True 
     break 

或者,更简洁的版本,使用内置any功能与发电机的表达:

list_to_match = sorted(a) 
combination_found = any(sorted(i) == list_to_match for i in e) 
0

对于您的特定问题,Python sets是一个更好的实现。

集合是包含数据的数学对象,但具有确定两个集合之间的工会,交集,差异等的方法。

使用:

set(a) == set(b) 

应该给你你想要的结果。只要“相似”,你的意思是“相同”。

0

不同的方式,而不for循环比较:

found = any(set(a)==set(l) for l in e) 
0
def checker(list_of_lists, example): 
    for i in list_of_lists: 
     if tuple(sorted(i)) == tuple(sorted(example)): 
      return True 
    return False