Python 3.x 在python中筛选不以特定名称开头的字符串

Python 3.x 在python中筛选不以特定名称开头的字符串,python-3.x,Python 3.x,我有一个数据库名称列表,我想排除那些以postgres开头的数据库名称 所以如果我有[“postgres”,“post”,“postgres2”,“custom1”,“custom2”] 结果应该是[“post”、“custom1”、“custom2”] 我尝试了两种不同的变体,但都没有得到我想要的结果: 要么: f_dbs=[d代表所有_dbs中的d,如果不是d.startswith(“postgres”)] 或: f_dbs=list(过滤器(lambda d:not d.startswit

我有一个数据库名称列表,我想排除那些以
postgres
开头的数据库名称

所以如果我有
[“postgres”,“post”,“postgres2”,“custom1”,“custom2”]
结果应该是
[“post”、“custom1”、“custom2”]

我尝试了两种不同的变体,但都没有得到我想要的结果:

要么:
f_dbs=[d代表所有_dbs中的d,如果不是d.startswith(“postgres”)]

或:
f_dbs=list(过滤器(lambda d:not d.startswith(“postgres”),all_dbs))

两者都不会从列表中排除任何内容。 我该怎么写

编辑: 我用过滤列表的额外用法更新了问题,输出也总是打印
postgres

编辑:
我发现了这个问题,列表中的所有项都有一个前导空格,在去除所有这些项后,它会按预期工作。

这些方法中的第一个创建一个新列表,而不是修改原始列表,第二个创建一个迭代器,您可以相当容易地将其转换为列表

list_of_dbs = [ "postgres", "post", "postgres2", "custom1", "custom2" ]

filtered_list = [item for item in list_of_dbs if not item.startswith("postgres")]

print(filtered_list)
>>> ['post', 'custom1', 'custom2']

filter_iterator = filter(lambda d: not d.startswith("postgres"), list_of_dbs)

print(filter_iterator)
>>><filter object at 0x10339d470>

print(list(filter_iterator))
>>>['post', 'custom1', 'custom2']
list\u of_dbs=[“postgres”、“post”、“postgres2”、“custom1”、“custom2”]
filtered_list=[如果不是item.startswith(“postgres”)的列表_中的项对应项]
打印(已筛选列表)
>>>['post'、'custom1'、'custom2']
filter\u iterator=filter(lambda d:not d.startswith(“postgres”),数据库列表)
打印(过滤器\迭代器)
>>>
打印(列表(过滤器\迭代器))
>>>['post'、'custom1'、'custom2']
你的第一个解决方案对我有效。您只需将其设置为一个变量:

>>> filtered_dbs = [d for d in all_dbs if not d.startswith('postgres')]
>>> filtered_dbs
['post', 'custom1', 'custom2']

您需要分配结果:
filtered_dbs=[d代表所有_dbs中的d,如果不是d.startswith(“postgres”)]
@l3via然后我分配了结果,更新了我的原始问题。您是否可以包括打印语句的输出以及所有_dbs列表的打印?当列表如您所述定义时,您的代码工作得非常好。
>>> all_dbs = [ "postgres", "post", "postgres2", "custom1", "custom2" ]
>>> [d for d in all_dbs if not d.startswith('postgres')]
['post', 'custom1', 'custom2']
>>> filtered_dbs = [d for d in all_dbs if not d.startswith('postgres')]
>>> filtered_dbs
['post', 'custom1', 'custom2']