繁体   English   中英

从 python function 中的列表中删除字符

[英]Removing characters from a list in python function

我正在尝试学习 python 中的函数,我遇到了以下问题的死胡同,我必须编写一个 function 以将字符串列表作为输入,删除特殊字符并返回包含干净字符串的列表。

代码如下所示:

def cleanChar(a):
   a=[]
   b=[',','?','#','@','$','%','^','&','*','/']
   out_list=[]

   for x in a:
       for y in b:
           if y in x:
               x=x.replace(y,'')
               out_list.append
   return out_list


testq = ['#mahesh','%Po*hsi$','Iy&gdj']

test3=cleanChar(testq)
print(test3)

我把输出作为一个空列表。 我在这里做错了什么或者我的方法应该是什么? 在此先感谢您的帮助。

我看到您的代码存在三个问题。

  1. 无需用[]重新初始化 function 参数a
  2. out_list.append应替换为out_list.append(x)
  3. out_list.append(x)必须与for y in b缩进级别相同。 这是因为一旦所有字符都被替换,我们只想将 append 到 output 列表。

所以你最终的 function 看起来像这样。

>>> def cleanChar(a):
...     b = [",", "?", "#", "@", "$", "%", "^", "&", "*", "/"]
...     out_list = []
...     for x in a:
...         for y in b:
...             if y in x:
...                 x = x.replace(y, "")
...         out_list.append(x)
...     return out_list
...
>>> testq = ["#mahesh", "%Po*hsi$", "Iy&gdj"]
>>> test3 = cleanChar(testq)
>>> print(test3)
['mahesh', 'Pohsi', 'Iygdj']
import re
clean_testq = [re.sub('[^a-zA-Z]',"",each) for each in testq]
clean_testq

['mahesh', 'Pohsi', 'Iygdj']

您可以运行一个简单的列表推导来检查输入中的元素是否不在b中,然后使用join()返回结果字符串。

def cleanChar(a):
    b=[',','?','#','@','$','%','^','&','*','/']
    return ''.join([element for element in a if element not in b])

testq = ['#mahesh','%Po*hsi$','Iy&gdj']

for i in testq:
    print(cleanChar(i))

输出

mahesh
Pohsi
Iygdj

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM