[英]How to filter out list elements that contain invalid characters in Python 3.x?
I am writing a function in Python 3.x that will take a list of string variables and a list of valid characters as arguments and return a filtered list containing elements of original list that are made up of valid characters only. 我在Python 3.x中编写一个函数,它将一个字符串变量列表和一个有效字符列表作为参数,并返回一个过滤列表,其中包含仅由有效字符组成的原始列表元素。 I think I can achieve the result using two nested For loops to iterate through list elements and then go through each character of the given element, but I want to know if there is a more efficient way to get this result using Python methods or functions.
我想我可以使用两个嵌套的For循环遍历列表元素然后遍历给定元素的每个字符来实现结果,但我想知道是否有更有效的方法来使用Python方法或函数获得此结果。
For the following two lists: 对于以下两个列表:
valid_characters = ['A','B','C']
my_list = ['abcde','AbCB','ABCBA','XYZ','CBCBB','CABzBAC']
The function would return filtered list ['ABCBA','CBCBB']
该函数将返回已过滤的列表
['ABCBA','CBCBB']
You can convert valid_characters
to a set so that you can efficiently determine if a string is made up purely of characters in the set by testing if the set is a superset of the characters in the string: 您可以将
valid_characters
转换为一个集合,以便通过测试该集合是否是字符串中字符的超集来有效地确定字符串是否纯粹由集合中的字符组成:
valid_set = set(valid_characters)
print([s for s in my_list if valid_set.issuperset(s)])
This outputs: 这输出:
['ABCBA', 'CBCBB']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.