简体   繁体   English

如何过滤掉Python 3.x中包含无效字符的列表元素?

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

相关问题 如何根据列表元素是否包含 Python 中另一个列表中的 substring 来过滤掉列表元素 - How to filter out list elements based on if they contain a substring from another list in Python 如何检查列表的前 n 个元素是否与 python 3.x 中的引用列表匹配? - How to check that first n elements of a list match a reference list in python 3.x? python 3.x上的列表索引超出范围错误 - List Index Out Of Range Error on python 3.x 如何过滤出不包含其他列表元素的列表列表? - How to filter out list of lists which doesn't contain elements from other list? 如何通过选择元素中的唯一字符组合来过滤列表(Python)? - How to filter the list by selecting for unique combinations of characters in the elements (Python)? Python 3.x-如何在两个字符串中查找字符集的交集 - Python 3.x - How to find the intersection of the sets of characters in two strings 如何使用python 3.x检测字符位置 - How to detect location of characters using python 3.x 循环,列表,python 3.x - loops, list, python 3.x 如何在Python 3.x中的链接列表中包含链接列表 - How to have a linked list within a linked list in Python 3.x Python 3.x通过列表中的公共元素动态地将2d列表中的元素分组 - Python 3.x dynamically group elements in 2d list by common elements in list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM