【问题标题】:How to find list items that are not in another list? [duplicate]如何查找不在另一个列表中的列表项? [复制]
【发布时间】:2019-12-31 01:59:36
【问题描述】:

例如,我有 2 个列表:

a = ['podcast', 'podcasts', 'history', 'gossip', 'finance', 'business', 'kids', 'motivation', 'news', 'investing']
b = ['podcast', 'history', 'gossip', 'finance', 'kids', 'motivation', 'investing']

我想在列表a 中查找不在列表b 中的项目

我尝试这样做:

c = []
for _ in a:
    if _ not in b:
        c.append(_)

我尝试的一切都以这样的方式结束:

最初,我有一个带有关键字的文本文件:

podcast
podcasts
history
gossip
finance

对于几乎所有关键字,我都有包含信息的文本文件:

podcast.txt
podcasts.txt
history.txt

我需要找到我丢失的文件 我加载了一个这样的关键字列表:

a = []
with open("keywords.txt", "r") as f:
    text = f.read().split("\n")
    for k in text:
        a.append(k)
b = [e.replace(".txt", "") for e in os.listdir("profiles/")]

【问题讨论】:

  • [i for i in a if i not in b]
  • c=[el for el in a if el not in b]。不值得回答
  • 我的意思是......我只是在盯着这个,我觉得这很有效。有什么问题?
  • @JoshuaSchlichting 我不知道为什么这对我不起作用
  • @kshnkvn 我刚刚运行了这个,它可以工作。你遇到了什么错误?

标签: python-3.x


【解决方案1】:

您可以使用列表推导:

 c = [i for i in a if i not in b]
 print(c)
 ['podcasts', 'business', 'news']

【讨论】:

  • 空列表。不要为我工作
【解决方案2】:

试试这个:

c = (set(a) - set(b))

【讨论】:

  • 不工作。空集
  • 你确定?我只是将它插入控制台,它对我来说很好用。 a = ['播客','播客','历史','八卦','金融','商业','孩子','动机','新闻','投资'] b = ['播客', “历史”、“八卦”、“金融”、“孩子”、“动机”、“投资”] c = (set(a) - set(b)) print(c)
  • 是的,我确定,它不起作用
  • @Mike kshnkvn 比问题中所揭示的更多。
  • 你能解释一下你所说的空集是什么意思吗?这是为您返回的内容,还是您收到错误?
【解决方案3】:

你可以尝试使用 numpy 吗?

import numpy as np
list1 = [.....]
list2 = [.....] 
diff = np.setdiff1d(list2,list1)

【讨论】:

  • array([], dtype='
猜你喜欢
  • 2020-01-08
  • 2022-11-12
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 2013-03-11
  • 2017-06-06
相关资源
最近更新 更多