how to compare elements of two list in python

a1.txt file has data which shows the student id and assignment marks:



student.txt file has data which shows the student id, first name, last name:



so, from the two file, I need an output of those students who have submitted assignments.

the output would be:

2345 roy,smith,8
9798 peter,jones,7

how can i get above output in python?

2 answers

  • answered 2018-05-16 05:54 mehrdad-pedramfar

    Try something like this:

    with open('a1.txt', 'r') as file1, open('student.txt', 'r') as file2:
        list_1 = file1.readlines()
        list_2 = file2.readlines()
        for i in list_1:
            i = i.split('|')
            for j in list_2:
                j = j.split('|')
                if i[0] == j[0]:
                    print(i[0], j[1], j[2].replace('\n', ''), i[1].replace('\n', ''), sep=",")  

  • answered 2018-05-16 05:57 Paul Panzer

    Convert one of the lists to dict for efficient lookup:

    >>> dict1 = {k: v for (k, *v) in list1}
    >>> result = [[k, *v, *dict1[k]] for (k, *v) in list2 if k in dict1]
    >>> result
    [['2345', 'roy', 'smith', '8'], ['9798', 'peter', 'jones', '7']]