繁体   English   中英

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

[英]Python - print items that are not in a list

我有一个包含以下内容的记事本:

banana
apple

另外,我有一个清单。 说: example_list = ["banana", "apple", "orange"]

我想在example_list中打印不在记事本中的值。 所以,期望的结果: orange

这是我试过的:

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)

这是打印:

banana
apple
orange

Python读取行尾字符以及每一行。 你必须把它剥掉。 类似fileLines = [x.strip() for x in file.readlines()]应该可以解决问题。

这将是第一次改变。 它回答了原始问题。

评论将激发改进算法的方法。 让他们燃烧。

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