在本例中,如何从Python列表中去除空白?

2024-05-08 19:08:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从列表中筛选出所有非字母数字字符。你知道吗

cleanlist = []
    for s in dirtylist:
        s = re.sub("[^A-Za-z0-9]", "", str(s)) 
        cleanlist.append(s)

从这个列表中过滤出空白的最有效的方法是什么?你知道吗


Tags: 方法inre列表for字母数字字符
3条回答

实际上,我会使用列表理解,但是你的代码已经很有效了。你知道吗

pattern = re.compile("[^A-Za-z0-9]")
cleanlist = [pattern.sub('', s) for s in dirtylist if str(s)]

另外,这是一个重复:Stripping everything but alphanumeric chars from a string in Python

最大的效率来自于使用正则表达式处理的全部功能:不要遍历列表。 其次,不要将单个字符从一个字符串转换为另一个字符串。非常简单:

cleanlist = re.sub("[^A-Za-z0-9]+", "", dirtylist)

为了确定这一点,我测试了几个列表理解和字符串替换方法;上面的方法至少快了20%。你知道吗

这将去除字符串中的空白,并且不会将空字符串添加到cleanlist

cleanlist = []
    for s in dirtylist:
        s = re.sub("[^A-Za-z0-9]", "", str(s).strip()) 
        if s:
            cleanlist.append(s)

相关问题 更多 >