如何删除列表中的字母和数字元素?下面的代码没有删除,我在做什么错呢?在研究了其他stackoverflow之后,他们正在删除字符,但未删除元素本身。
ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
cleaned = [x for x in ls if x is not x.isalnum() or x is not x.isdigit()]
cleaned
result = re.sub(r'[^a-zA-Z]', "", ls)
print(result) #expected string or bytes-like object
输出应为:
['apples','oranges','mangoes']
enter code here
答案 0 :(得分:2)
尝试一下:
ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
[l for l in ls if l.isalpha()]
输出:
['apples', 'oranges', 'mangoes']
答案 1 :(得分:0)
尝试:-
ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
l = []
for i in ls:
if not bool(re.search(r'\d', i)):
l.append(i)
print(l)
答案 2 :(得分:0)
我会这样:
newList = []
for x in ls:
if x.isalpha():
newList.append(x)
print(newList)
对我有用。如果元素不包含数字,则只会将其添加到新列表中。