简体   繁体   English

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

[英]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.

相关问题 在列表中找到与其他元素不同的元素的最pythonic方法是什么? - what is most pythonic way to find a element in a list that is different with other elements? 什么是确保列表中所有元素不同的最pythonic方法? - What's the most pythonic way to ensure that all elements of a list are different? 列表边界-最Python的方式是什么? - List boundaries - what is the most Pythonic way? 从迭代器中排除特殊值的最pythonic 方法是什么? - What is the most pythonic way to exclude a special value from an iterator? 从字符串的开头删除数字的最Pythonic方法是什么? - What's the most Pythonic way to remove a number from start of a string? 在列表的每个X元素之后添加特定字符的pythonic方法是什么? - What's the pythonic way to add a certain character after every X elements of a list? 查找列表中两个元素之间关系的最pythonic方法 - Most pythonic way to find relation between two elements in a list 在列表中循环直到特定值的最pythonic方式是什么? - What is the most pythonic way of looping in a list until a particular value? 忽略带有括号的列表中的单词的最有效(pythonic)方法是什么? - What is the most efficient (pythonic) way to ignore words in a list that has parantheses? 重构此列表构建代码的最Pythonic方法是什么? - What's the most Pythonic way to refactor this list building code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM