Search code examples
pythonlistchartscomparison

Python comparing multiple lists into Comparison Table


I'm not looking for an exact solution but looking for a keyword to research on. Not sure why but I really couldn't manage to find any examples for this very simple problem.

Lets assume I got 3 lists(could be more) that looks this:

l1=[x,y,z]
l2=[a,y,z,b]
l3=[a,b,c,d,e]

and what I'm trying to do is to have an comparison table looks like this:

    l1  l2  l3
a   0   1   1
b   0   1   1
c   0   0   1
d   0   0   1
e   0   0   1
x   1   0   0
y   1   1   0
z   1   1   0

lists can be in different length and they never have repetitions like:

l = [x,x,y]

again I'm not asking for someone to handle the task for me but I'm just looking for some keywords, advices, pseudo code to get things started.


Solution

  • It may not be the fastest or the most efficient solution but I did it this way. I create a dictionary with keys being the values in all of the lists. Values being the which list the appear in. Then I print the headers (List names) and each key and values line by line. I am pretty sure there is a better way of doing this than my solution.

    l1=["x","y","z"]
    l2=["a","y","z","b"]
    l3=["a","b","c","d","e"]
    
    values = sorted(set(l1 + l2 + l3))
    
    d = {}
    for value in values:
        x = []
        if value in l1:
            x.append("1")
        else:
            x.append("0")
            
        if value in l2:
            x.append("1")
        else:
            x.append("0")
            
        if value in l3:
            x.append("1")
        else:
            x.append("0")
        d[value] = x
    
    print(" "*3 + "l1 l2 l3")
    
    for k in d:
        print(k + " "*2 + "  ".join(d[k]))