繁体   English   中英

如何从 Python 的列表中仅获取特定项目

[英]How to get only specific items from list in Python

我只想从列表中获取特定项目(A027SRR,B09P4RR,C09QMRR,C09MIRR,A026SRR,A0CDDRR,B0NOTRR) ,但不幸的是不起作用,我不知道哪里有问题。谢谢

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

只需使用过滤器 function 并将其转换为列表。 您没有 state 要过滤的条件。 根据您的问题,如果其中任何一个条件为真,则您想要删除一个项目,而不是如果所有条件都为真。 这意味着您必须使用or分离条件。 同样isdigit()islower()已经返回TrueFalse ,你不需要用另一个True检查它, isdigit()而不是isdigit() == True

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

您也可以使用any

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

如果条件为真,您不想保留项目,您可以使用itertools.filterfalse ,您不必添加not

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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