gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:10:46 24 4
gpt4 key购买 nike

我有一个字典,其中包含作为键的字符串和作为值的列表。

我想删除所有包含字符串“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))

电流输出示例

 "role_thumper": [
"thumper-msatl1-prod-1.env.fake.com",
"thumper-msatl1-prod-2.env.fake.com",
"thumper-rwva1-prod-1.env.fake.com",
"thumper-rwva1-prod-2.env.fake.com",
"thumper-rwva1-prod-3.env.fake.com",
"thumper-rwva1-prod-4.env.fake.com",
"thumper-rwva1-prod-5.env.fake.com",
"thumper-rwva1-prod-6.env.fake.com",
"thumper-staging-1.env.fake.com"
],
"role_thumper_mongo": [
"thumper-mongo-staging-1.env.fake.com",
"thumper-mongo-staging-2.env.fake.com",
"thumpermongo-rwva1-staging-1.env.fake.com",
"thumpermongo-rwva1-staging-2.env.fake.com"
],
"role_thumper_mongo_arb": [
"thumper-mongo-arb-staging-1.env.fake.com",
"thumpermongo-arb-rwva1-staging-1.env.fake.com"
],

最佳答案

列表理解就是你所追求的

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

这只是 for 循环的简写。

x_filtered = []
for i in x:
if "a" not in i:
x_filtered.append(i)

关于Python从数组中删除匹配模式的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44011518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com