Search code examples
pythonlistloopsmultidimensional-arraylist-comparison

comparing elements in list of lists


I basically have a list of lists like this: [['sd', 'pd', 'od'], ['sd', 'pd1', 'od2'], ['sd2', 'pd2', 'od']] and I want the output to be ['sd pd od ; pd1 od2 .', 'sd2 pd2 od .'] So, I want to compare the first element of each list with each other and if they are the same, I want to leave out the first element (that occurs in the second list).

Here is my code which doesn't work as it compares the elements too much and I don't know why.

def simplistic(triples):
base = []
for x in triples:
    for y in triples:
        if x[0] == y[0]:
            base.append((x[:],y[1],y[2]))
print(base)

The output of this code is:

[(['sd', 'pd', 'od'], 'pd', 'od'), (['sd', 'pd', 'od'], 'pd1', 'od2'), (['sd', 'pd1', 'od2'], 'pd', 'od'), (['sd', 'pd1', 'od2'], 'pd1', 'od2'), (['sd2', 'pd2', 'od'], 'pd2', 'od')]

Solution

  • As you question is a little unclear, try this and check is it ok or not.

    bad_list = []
    f=''
    for i,s in enumerate(l):
        if s[0] == l[i-1][0] or s[0] in bad_list:
            f = f + ' '.join(s[1:])
            bad_list.append(s[0])           
        else:
            f = f + ' '.join(s)
        f = f+ ' ;'
    f = [f[:-1] + '.']
    

    The f will be your expected result.