简体   繁体   English

迭代一个 Python 列表并根据另一个列表过滤元素

[英]Iterate a Python list and filter the elements based on another list

I have two lists.我有两个列表。 The first list has all the names.第一个列表包含所有名称。

firstList = ["mike", "mary", "steve", "jane"]

The second list contains the name I want to filter.第二个列表包含我要过滤的名称。

filteredList = ["mike", "mary"]

I want to exclude all names in the filtered list so that the final list looks like this:我想排除过滤列表中的所有名称,以便最终列表如下所示:

finalList = ["steve","jane"]

The names are examples and the number of entries will vary and needs to be dynamic.名称是示例,条目的数量会有所不同并且需要是动态的。

I started with this but it didn't run:我从这个开始但它没有运行:

for b in firstList:
    for s in filteredList:
        finalList = firstList[firstList[b != s]]
        print(finalList)

Thoughts?想法? Any help would be appreciated.任何帮助,将不胜感激。

You can use list comprehension to achieve this:您可以使用列表理解来实现此目的:

firstList = ["mike", "mary", "steve", "jane"]
filteredList = ["mike", "mary"]

finalList = [name for name in firstList if name not in filteredList]
# where `finalList` will hold: ['steve', 'jane']

Here you are iterating the firstList and checking the presence of each item in filteredList .在这里,您正在迭代firstList并检查filteredList中每个项目的存在。 If not present, consider it for your new list.如果不存在,请考虑将其用于您的新列表。

You can also use set() to achieve this as:您还可以使用set()来实现此目的:

set(firstList) - set(filteredList)
# returns: set(['steve', 'jane'])

# if it is must for you to obtain the "finalList" as `list`, 
# you can type-cast it as:
#     finalList = list(set(firstList) - set(filteredList))

But via using set, you won't be able to preserve the order of these names in the firstList .但是通过使用 set,您将无法在firstList中保留这些名称的顺序。 And it will hold only unique items ie repetitive items will be removed.它将只保存唯一的项目,即重复的项目将被删除。 For example: if your "firstList" will contain ["mike", "mike", "mary", "steve", "jane"] , finalList will just contain single "mike" whereas in the list comprehension based solution I proposed above, you'll see "mike" twice.例如:如果您的“firstList”将包含["mike", "mike", "mary", "steve", "jane"]finalList将只包含单个"mike" ,而在我上面提出的基于列表理解的解决方案中,您会看到两次"mike"


In the code you shared, it could be fixed as:在您共享的代码中,它可以固定为:

finalList = []

for b in firstList:
    if b not in filteredList: # checking the presence of "b" in "filteredList"
        finalList.append(b)

# where `finalList` will contain: ['steve', 'jane']

Use numpy.setdiff1d使用numpy.setdiff1d

#import numpy as np
np.setdiff1d(firstList, filteredList).tolist()

or set with - operator或使用-运算符set

list(set(firstList) - set(filteredList))

or filterfilter

list(filter(lambda x: x not in filteredList, firstList))

Output Output

['steve', 'jane']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM