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

时间:2019-01-29 01:34:19

标签: python 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

3 个答案:

答案 0 :(得分:1)

Python读取行尾字符以及每一行。您必须将其剥离。像Private Sub cmbAdd_Click() Dim sheet As Worksheet Set sheet = ThisWorkbook.Sheets("TRY TRY") nextrow = sheet.Cells(Rows.Count, 1).End(xlUp).Row + 1 sheet.Cells(nextrow, 1) = Me.cmbSchema sheet.Cells(nextrow, 2) = Me.cmbEnvironment sheet.Cells(nextrow, 3) = Me.cmbHost sheet.Cells(nextrow, 4) = Me.cmbIP sheet.Cells(nextrow, 5) = Me.cmbAccessible sheet.Cells(nextrow, 6) = Me.cmbLast sheet.Cells(nextrow, 7) = Me.cmbConfirmation sheet.Cells(nextrow, 8) = Me.cmbProjects MsgBox "Data Added!" End Sub 之类的方法就可以解决问题。

这是要进行的第一更改。它回答了原始问题。

使用改进算法的方法会引起评论的轰动。让他们燃烧。

答案 1 :(得分:1)

str.join

l= set(map(str.rstrip,fileLines))
print('\n'.join([i for i in list if i not in l]))

答案 2 :(得分:1)

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