Python从数组中移除匹配模式的元素

2024-04-29 16:03:24 发布

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

我有一个字典,它包含字符串作为键,列表作为值。在

我想删除所有包含字符串“food”、“staging”、“msatl”和“azeus”的列表元素。我已经有了下面的代码,但是很难将filterIP中的逻辑应用到其他字符串中。在

    def filterIP(fullList):
       regexIP = re.compile(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$')
       return filter(lambda i: not regexIP.search(i), fullList)

    groups = {key : [domain.replace('fake.com', 'env.fake.com')
      for domain in filterIP(list(set(items)))]
        for (key, items) in groups.iteritems() }

    for key, value in groups.iteritems():
      value.sort()

    meta = { "_meta" : { "hostvars" : hostvars } }
    groups.update(meta)

    print(self.json_format_dict(groups, pretty=True))

电流输出示例

^{pr2}$

Tags: key字符串incom列表fordomainitems
3条回答

完成任务的一个简单方法是遍历字典中的每个列表。根据条件创建新列表,并将新列表分配给新字典中相同的键。下面是代码中的情况:

def filter_words(groups, words):
    d = {}
    for key, domains in groups.iteritems():
        new_domains = []
        for domain in domains:
            if not any(word in domain for word in words):
                new_domains.append(domain)
        d[key] = new_domains
    return d

你可以这样称呼它:

groups = filter_words(groups, {"food", "staging", "msatl" and "azeus"})

上面代码的“肉”是第二个for循环:

^{pr2}$

这段代码遍历当前键列表中的每个字符串,并根据无效单词的列表筛选出所有无效的字符串。

清单理解就是你想要的

x= ["a", "b", "aa", "aba"]
x_filtered = [i for i in x if "a" not in i]
print(x_filtered)
>>> ['b']

这只是for循环的简写。

^{pr2}$

如果我没听错,这可能会有帮助。

设置排除列表:

exclude=  ["food", "staging", "msatl", "azeus"]

测试列表(我在您的示例中找不到实例)

^{pr2}$

运行列表理解(迭代器的名称无关紧要,您可以选择更合适的迭代器)

result= [i for i in test if not any([e for e in exclude if e in i])]

result ['a']

上面@Julian的回答很好地解释了列表理解的作用。这使用其中的两个,如果在排除列表中有任何匹配,any部分是True
希望这有帮助。

相关问题 更多 >