简体   繁体   中英

Remove items from a list in Python using conditions

I need to remove all values from a set of lists inside a list which are string or lower than 28. Any help?

a[1:3]

a = [[u'ufs_munic', u'ext_paises', u'5', u'6', u'7', u'8', u'5551', u'5552', u'5553', u'5554', u'5555', u'5556', u'5557'], [u'ufs_munic', u'ext_paises', u'5', u'6', u'7', u'8', u'9', u'10', u'11', u'12', u'5301', u'5302', u'289', u'5303', u'5304', u'5305', u'290', u'5306', u'5307', u'5308', u'5309', u'291', u'5310', u'5311', u'5312', u'5313', u'5314', u'5315', u'5316', u'5317', u'292', u'5318', u'5319', u'5320']]

I need to get a result like:

[[u'5551', u'5552', u'5553', u'5554', u'5555', u'5556', u'5557'], [u'5301', u'5302', u'289', u'5303', u'5304', u'5305', u'290', u'5306', u'5307', u'5308', u'5309', u'291', u'5310', u'5311', u'5312', u'5313', u'5314', u'5315', u'5316', u'5317', u'292', u'5318', u'5319', u'5320']]

Use filter .

def passed(item):
    try:
       return int(item) > 28
    except ValueError:
       return False
result = [filter(passed, item) for item in a] 

Variation on the filter theme. This won't work if your number is so big it overflows on conversion to something less than 28 :)

map(lambda lst : filter(lambda v : v.isdigit() and float(v) > 28, lst),a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM