如何删除列表中的多个字符?

发布于 2021-01-29 17:29:43

有这样的清单:

x = ['+5556', '-1539', '-99','+1500']

我怎样才能很好地删除+和-?

这有效,但我正在寻找更多的pythonic方式。

x = ['+5556', '-1539', '-99', '+1500']
n = 0
for i in x:
    x[n] = i.replace('-','')
    n += 1
n = 0
for i in x:
    x[n] = i.replace('+','')
    n += 1
print x

编辑

+而且-并不总是处于领先地位;他们可以在任何地方。

关注者
0
被浏览
37
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用str.strip()或最好str.lstrip()

    In [1]: x = ['+5556', '-1539', '-99','+1500']
    

    使用list comprehension

    In [3]: [y.strip('+-') for y in x]
    Out[3]: ['5556', '1539', '99', '1500']
    

    使用map()

    In [2]: map(lambda x:x.strip('+-'),x)
    Out[2]: ['5556', '1539', '99', '1500']
    

    编辑:

    如果您同时也在数字之间,请使用@Duncan提供的str.translate()基础解决方案。+``-

    使用string.translate(),或用于Python 3.x str.translate:

    Python 2.x:

    >>> import string
    >>> identity = string.maketrans("", "")
    >>> "+5+3-2".translate(identity, "+-")
    '532'
    >>> x = ['+5556', '-1539', '-99', '+1500']
    >>> x = [s.translate(identity, "+-") for s in x]
    >>> x
    ['5556', '1539', '99', '1500']
    Python 2.x Unicode:
    
    >>> u"+5+3-2".translate({ord(c): None for c in '+-'})
    u'532'
    

    Python 3.x版本:

    >>> no_plus_minus = str.maketrans("", "", "+-")
    >>> "+5-3-2".translate(no_plus_minus)
    '532'
    >>> x = ['+5556', '-1539', '-99', '+1500']
    >>> x = [s.translate(no_plus_minus) for s in x]
    >>> x
    ['5556', '1539', '99', '1500']
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看