简体   繁体   中英

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

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
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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM