[英]What is the most pythonic way to exclude elements of a list that start with a specific character?
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?)
(最好不要使用循环?)
[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中使用循环。
Not using a loop? 不使用循环? There is
filter
builtin: 内置
filter
:
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()
包装它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.