【问题标题】:How to remove 0.1% from a list?如何从列表中删除 0.1%?
【发布时间】:2021-09-20 15:45:22
【问题描述】:

我有以下列表

data = [    '0.1%',
 'hello',
 'how are you guys',
  '0.1%',
  '1%',
 '0.1%',
  '1%', ]

我试过这个:

cell = float(data.rstrip("%"))

我想去掉 1% 和 0.1%

预期输出:

    data = [ 'hello','how are you guys' ]    

【问题讨论】:

  • 那么,您尝试过什么?如果你知道循环是如何工作的,或者列表推导是如何工作的,这看起来很容易。你看过 python.org 上的教程了吗?
  • [x for x in data if '%' not in x] ?
  • rstrip 仅适用于单个字符串,不适用于字符串列表。可能只有在pandas.DataFrame 中,您可以使用dataframe.str.rstrip('%') 将其从表中的所有元素中删除。在纯 Python 中,您必须为此使用 for-loop。

标签: python arrays regex list tuples


【解决方案1】:

给你:

new_list = [d for d in data if d not in ['0.1%', '1%']]

【讨论】:

    【解决方案2】:

    如果你想使用更通用的东西:

    result = []
    for i in data:
        try:
            float(i.strip('%'))
        except:
            result.append(i)
    

    输出:

    ['hello', 'how are you guys']
    

    【讨论】:

      【解决方案3】:

      这是另一种巧妙的方法!

      data = ['0.1%',
          'hello',
          'how are you guys',
          '0.1%',
          '1%',
          '0.1%',
          '1%', ]
      
      unwanted = [0, 3, 4, 5, 6,]
      
      for ele in sorted(unwanted, reverse=True):
          del data[ele]
      
      
      print(data)
      

      【讨论】:

        猜你喜欢
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        • 2021-04-29
        • 1970-01-01
        • 2012-10-26
        • 1970-01-01
        • 2014-03-13
        • 2021-03-18
        相关资源
        最近更新 更多