[英]Python remove only alphabet elements from a list
I have a very messy data, I am trying to remove elements that contains alphabets or words. 我的数据非常混乱,我正在尝试删除包含字母或单词的元素。 I am trying to capture the elements that have alphanumerical and numerical values.
我正在尝试捕获具有字母数字和数字值的元素。 I tried .isalpha() but it not working.
我尝试了.isalpha(),但是没有用。 How do I remove this?
我该如何删除?
lista = ['A8817-2938-228','12421','12323-12928-A','12323-12928',
'-','A','YDDEWE','hello','world','testing_purpose','testing purpose',
'A8232-2938-228','N7261-8271']
lista
Tried: 尝试:
[i.isalnum() for i in lista] # gives boolean, but opposite of what I need.
Output: 输出:
['A8817-2938-228','12421','12323-12928-A','12323-12928','-','A8232-2938-228','N7261-8271']
Thanks! 谢谢!
You can add conditional checks in list comprehensions, so this is what you want: 您可以在列表推导中添加条件检查,因此您需要这样做:
new_list = [i for i in lista if not i.isalnum()]
print(new_list)
Output: 输出:
['A8817-2938-228', '12323-12928-A', '12323-12928', '-', 'testing_purpose', 'testing purpose', 'A8232-2938-228', 'N7261-8271']
Note that isalnum
won't say True
if the string contains spaces or underscores. 请注意,如果字符串包含空格或下划线,则
isalnum
不会说True
。 One option is to remove them before checking: (You also need to use isalpha
instead of isalnum
) 一种选择是在检查之前将其删除:(您还需要使用
isalpha
而不是isalnum
)
new_list_2 = [i for i in lista if not i.replace(" ", "").replace("_", "").isalpha()]
print(new_list_2)
Output: 输出:
['A8817-2938-228', '12421', '12323-12928-A', '12323-12928', '-', 'A8232-2938-228', 'N7261-8271']
What type your data in the list? 列表中的数据类型是什么?
You can try to do this: 您可以尝试这样做:
[str(i).isalnum() for i in lista]
It seems you can just test at least one character is a digit or equality with '-'
: 看来您可以测试至少一个字符是数字或与
'-'
相等的字符:
res = [i for i in lista if any(ch.isdigit() for ch in i) or i == '-']
print(res)
['A8817-2938-228', '12421', '12323-12928-A', '12323-12928',
'-', 'A8232-2938-228', 'N7261-8271']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.