Warm tip: This article is reproduced from stackoverflow.com, please click
list python python-3.6

How do I individually print items of a list that are in another list in python

发布于 2020-03-27 10:32:16

I want to individually print(and then write to a file) items of a list that are in another list. If there are no matching items then I want 'NONE' to be printed. I have a time limit on my program, so I would like a quick and easy solution to this, preferable under 0.1 seconds.

I have a list called joinedComb, and I want to individually print all items in joinedComb that are in another list called dictionary I have tried

for i in joinedCombs:
    if i in dictionary:
        endResult.append(i)
        fout.write(i+'\n')
if endResult == []:
    fout.write('NONE\n')

I would like it to print something like this:

GREG
GEKA
GENO

or

NONE
Questioner
user11735387
Viewed
77
magma 2019-07-05 06:36
endResult = [i for i in joinedCombs if i in dictionary] 
fout = '\n'.join(endResult) if any(endResult) else 'NONE'

If you prefer, it is possible to do it without loops. You can use logical conjuction of two sets but don't expect execution time shortening.

endResult = set(joinedCombs).intersection(set(dictionary.keys()))