简体   繁体   中英

How to get only specific items from list in Python

I would like to get only specific items (A027SRR,B09P4RR,C09QMRR,C09MIRR,A026SRR,A0CDDRR,B0NOTRR) from the list but unfortunately is not working and I dont know where is an issue.Thank you

items = ['A027SRR', '0.00', '', 'B09P4RR', '852.00', '', 'C09QMRR', '309.60', '', 'C09MIRR', '18.70', '', 'A026SRR', '78.40', '', 'A0CDDRR', 'B0NOTRR', '', '1543.52', '1481.52', "VIP discount :   20.01%  \VIP discount's information"]
for f in items[:]:   # check if character is number then check if is empty then if is lower case then chceck if lenght is seven 
    if f.isdigit() == True and f =='' and f.islower()== True and len(f) != 7 :          
    items.remove(f)
print(" Items are : " + str(items))

If you want a regex solution:

If a string is having atleast 1 Upper Case letter and atleast 1 number and is of length 7

reg=re.compile("^(?=.{7}$)(?=.*\d)(?=.*[A-Z]).*")
list(filter(reg.search, items))

['A027SRR', 'B09P4RR', 'C09QMRR', 'C09MIRR', 'A026SRR', 'A0CDDRR', 'B0NOTRR']

Simply use the filter function and convert it to a list. You do not state the criteria based on which you want to filter. As per your question, you want to remove an item if any one of those conditions are true not if all of them are true. Which means you'll have to use or to separate the conditions. Also isdigit() and islower() already return True or False , you don't need to check it with another True , isdigit() instead of isdigit() == True

final_list = list(filter(lambda f: not (f.isdigit() or f =='' or f.islower() or len(f) != 7), items[:]))

You can also use any :

final_list = list(filter(lambda f: not any([f.isdigit(),f =='', f.islower(),len(f) != 7]), items[:]))

Since you do not want to keep the items if the condition is true, you can use itertools.filterfalse , you will not have to add the not :

from itertools import filterfalse
final_list = list(filterfalse(lambda f: f.isdigit() or f =='' or f.islower() or len(f) != 7, items[:]))

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