【问题标题】:python remove alphanum and numbers elements in a list [duplicate]python删除列表中的字母和数字元素[重复]
【发布时间】:2018-07-19 17:06:03
【问题描述】:

如何删除列表中的字母和数字元素?下面的代码没有删除,我在这里做错了什么?在对其他 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

【问题讨论】:

  • 如果你只想要字母字符,为什么不检查str.isalpha[x for x in ls if x.isalpha()]?你关心标点符号吗?

标签: python python-3.x


【解决方案1】:

试试这个:

ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']

[l for l in ls if l.isalpha()]

输出:

['apples', 'oranges', 'mangoes']

【讨论】:

    【解决方案2】:

    试试这个:-

    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)
    

    【讨论】:

      【解决方案3】:

      我会这样做:

      newList = []
      for x in ls:
          if x.isalpha():
              newList.append(x)
      
      print(newList)
      

      它对我有用。如果元素不包含数字,它只会将元素添加到新列表中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        相关资源
        最近更新 更多