简体   繁体   English

Python - 打印不在列表中的项目

[英]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"] 说: example_list = ["banana", "apple", "orange"]

I want to print the values in example_list, that are not inside the notepad. 我想在example_list中打印不在记事本中的值。 So, desired outcome: orange 所以,期望的结果: 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. Python读取行尾字符以及每一行。 You'll have to strip it off. 你必须把它剥掉。 Something like fileLines = [x.strip() for x in file.readlines()] should do the trick. 类似fileLines = [x.strip() for x in file.readlines()]应该可以解决问题。

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 : 或者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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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