如何从列表中删除0.1%的内容?

yv5phkfx  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(503)

我有以下清单

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' ]
vlurs2pr

vlurs2pr1#

干得好:

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

monwx1rj2#

如果您想使用更通用的方法:

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

输出:

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

mqxuamgl3#

这是另一个狡猾的方式做到这一点!

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)

相关问题