[英]Remove elements from python list if they contain special characters
I have a python list of lists, where each row index represents a list of values.我有一个 python 列表列表,其中每个行索引代表一个值列表。 In some instances, the row values contain special characters.
在某些情况下,行值包含特殊字符。 In the case that any list element in the row contains special characters, I want to remove that entire row from the list.
如果行中的任何列表元素包含特殊字符,我想从列表中删除整行。 Note that I want to do this without converting the list into a NumPy array or pandas data frame.
请注意,我想在不将列表转换为 NumPy 数组或 pandas 数据帧的情况下执行此操作。 I was thinking of checking the row index that contains special characters and then just removing them this way but not sure how to do it with just a python list.
我正在考虑检查包含特殊字符的行索引,然后以这种方式删除它们,但不知道如何仅使用 python 列表来执行此操作。 The other alternative is to convert into a NumPy array, do the data cleaning, and then convert back into the original list format but maintaining the original structure.
另一种选择是转换为 NumPy 数组,进行数据清理,然后转换回原始列表格式但保持原始结构。
testList = [[30.0, '?', 910.0, 120.],[11.0, 25.4, 330.3, 340.0], [1.6, 23.4, 23.0, 46.0], [7.0,14.0,?,2.0], ['*', '*', 8.9, 6.4]]
newList = [[11.0, 25.4, 330.3, 340.0], [1.6, 23.4, 23.0, 46.0]]
You can use any
within list comprehension
to filter out list
s that have str
s using isinstance
:您可以使用
list comprehension
推导中的any
来过滤出使用isinstance
的具有str
的list
:
>>> testList = [[30.0, '?', 910.0, 120.],[11.0, 25.4, 330.3, 340.0], [1.6, 23.4, 23.0, 46.0], [7.0,14.0,'?',2.0], ['*', '*', 8.9, 6.4]]
>>> [subL for subL in testList if not any(isinstance(val, str) for val in subL)]
[[11.0, 25.4, 330.3, 340.0], [1.6, 23.4, 23.0, 46.0]]
Why not just create a qualifier function, then use list comprehension to create the new list?为什么不创建一个限定符 function,然后使用列表推导来创建新列表?
def keep_me(element):
# analyze the element, and return True to keep, or False to drop
return True
Then to use:然后使用:
filtered_list = [x for x in original_list if keep_me(x)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.