排除以特定字符开头的列表元素的最pythonic方法是什么?

时间:2021-10-13 22:09:11

I have a list of strings. I want to get a new list that excludes elements starting with '#' while preserving the order. What is the most pythonic way to this? (preferably not using a loop?)

我有一个字符串列表。我希望得到一个新的列表,在保留订单的同时排除以“#”开头的元素。什么是最蟒蛇的方式? (最好不要使用循环?)

2 个解决方案

#1


24  

[x for x in my_list if not x.startswith('#')]

That's the most pythonic way of doing it. Any way of doing this will end up using a loop in either Python or C.

这是最狡猾的做法。任何这样做的方式最终都会在Python或C中使用循环。

#2


8  

Not using a loop? There is filter builtin:

不使用循环?内置过滤器:

filter(lambda s: not s.startswith('#'), somestrings)

Note that in Python 3 it returns iterable, not a list, and so you may have to wrap it with list().

请注意,在Python 3中它返回iterable而不是列表,因此您可能必须使用list()包装它。

#1


24  

[x for x in my_list if not x.startswith('#')]

That's the most pythonic way of doing it. Any way of doing this will end up using a loop in either Python or C.

这是最狡猾的做法。任何这样做的方式最终都会在Python或C中使用循环。

#2


8  

Not using a loop? There is filter builtin:

不使用循环?内置过滤器:

filter(lambda s: not s.startswith('#'), somestrings)

Note that in Python 3 it returns iterable, not a list, and so you may have to wrap it with list().

请注意,在Python 3中它返回iterable而不是列表,因此您可能必须使用list()包装它。