[英]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我只想从列表中获取特定项目
(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 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.只需使用过滤器 function 并将其转换为列表。 You do not state the criteria based on which you want to filter.
您没有 state 要过滤的条件。 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.这意味着您必须使用
or
分离条件。 Also isdigit()
and islower()
already return True
or False
, you don't need to check it with another True
, isdigit()
instead of isdigit() == True
同样
isdigit()
和islower()
已经返回True
或False
,你不需要用另一个True
检查它, isdigit()
而不是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
:您也可以使用
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
:如果条件为真,您不想保留项目,您可以使用
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.