Python打印不在lis中的项目

2024-03-29 11:15:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

banana
apple

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

我想打印示例\u列表中不在记事本中的值。所以,期望的结果: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

Tags: intxt示例apple列表exampleopenitem
3条回答
>>> 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

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

相关问题 更多 >