简体   繁体   中英

Python - print items that are not in a list

I have a notepad that contains the following:

banana
apple

Additionally, I have a list. Say: example_list = ["banana", "apple", "orange"]

I want to print the values in example_list, that are not inside the notepad. So, desired outcome: orange

This is what I tried:

file = open("picturesLog.txt", "r")
fileLines = file.readlines()

example_list = ["banana", "apple", "orange"]

for item in example_list:
    if item in fileLines:
        pass
    else:
        print(item)

This is printing:

banana
apple
orange

Python reads the end-of-line character along with each line. You'll have to strip it off. Something like fileLines = [x.strip() for x in file.readlines()] should do the trick.

That would be the first change to make. It answers the original question.

The comments will be aflame with ways to improve the algorithm. Let them burn.

Or str.join :

l= set(map(str.rstrip,fileLines))
print('\n'.join([i for i in list if i not in l]))
>>> example_list = ["banana", "apple", "orange"]
>>> with open("picturesLog.txt") as f: 
...   seen = set(map(str.strip, f))
...   for fruit in set(example_list) - seen:
...     print(fruit)
... 
orange

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