簡體   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