如何找出不在另一个列表中的列表项?

4
例如,我有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(_)

我尝试的所有方法都以这样的结果结束:

image

一开始,我有一个包含关键词的文本文件:

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] - Onyambu
c=[el for el in a if el not in b]。不值得回答。 - Pynchia
我的意思是...我只是凭感觉做的,我觉得这个可行。有什么问题吗? - Joshua Schlichting
@JoshuaSchlichting 我不知道为什么这对我不起作用。 - kshnkvn
另外,在下一个问题中使用更具描述性的问题名称,否则相同的问题名称会很快被关闭! - Joshua Schlichting
显示剩余6条评论
3个回答

8
你可以使用列表推导式:
 c = [i for i in a if i not in b]
 print(c)
 ['podcasts', 'business', 'news']

空列表。对我不起作用。 - kshnkvn

7

尝试这个:

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

不工作。空集合。 - kshnkvn
你确定吗?我刚将它插入控制台,它对我很好用。 a = ['播客', '播客节目', '历史', '八卦', '财务', '商业', '孩子', '动力', '新闻', '投资'] b = ['播客', '历史', '八卦', '财务', '孩子', '动力', '投资']c = (set(a) - set(b)) print(c) - Mike
是的,我确定,它没有工作。 - kshnkvn
1
@Mike kshnkvn在问题中透露的不只是这些。 - Joshua Schlichting
你能澄清一下“空集合”的含义吗?这是你得到的返回值,还是出现了错误? - Mike
更新了一个问题。 - kshnkvn

2

你可以尝试使用numpy吗?

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

数组([], dtype='<U22') - kshnkvn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接