比较两个列表(值)和geht True / False回

时间:2017-08-02 05:12:56

标签: python list compare

我想用一段python代码解决Nodebox3中的一个问题。这是Nodebox 3中缺少的功能。这是我的问题:

我想比较两个不同列表的值并创建一个新的输出列表。新列表应包含列表1和列表2中的详细信息以及比较过程的结果。 (对或错)

List1和List2中的数字在列表中只存在一次,但它们可能是未排序的,并且每次加载时在每个列表的不同位置(索引)。

My idea Compare Lists and Result

Values List 1 (Master): App1 
1
2
3
4
5

Values List 2 (Compare to List 1): App2
2
4

Output (list with Header):
App1    App2    CompareResult   
1       0       False
2       2       True    
3       0       False 
4       4       True 
5       0       False 

我试图自己创建一些代码,但我是编程的新手,它不会给我回复的结果,我正在寻找。它只显示匹配的数字。这就是全部。也许有人知道我是如何得到错误的结果的。

My Code

def matches_out(list1, list2):
    set1 = set(list1)
    set2 = set(list2)
    # set3 contains all items common to set1 and set2
    set3 = set1.intersection(set2)
    #return matches
    found = []
    for match in set3:
        found.append(match)
    return found

如果有人有想法,谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

检查两个列表的交集是正确的,但只有解决方案的一半,因为它只找到匹配项。您还想报告不匹配,为此您还需要两个列表的并集。

list1 = [1,2,3,4,5]
list2 = [2,4]
matches = set(list1).intersection(list2)
candidates = set(list1).union(list2)
result1 = []  # 1st column of output
result2 = []  # 2nd column of output
for c in sorted(candidates):
    result1.append(c if c in list1 else 0)
    result2.append(c if c in list2 else 0)
for i in range(len(result1)): 
    print ("{0}\t{1}\t{2}\t".format(result1[i], result2[i], result1[i]==result2[i]))

产生此输出:

1   0   False   
2   2   True    
3   0   False   
4   4   True    
5   0   False   

如果相同的数字在列表中出现多次,则不清楚您想要发生什么。你的代码忽略了重复,所以我跟着同一行。

我会留下添加标题给你。

编辑:OP报告固定cut'n'paste错误。

相关问题