簡體   English   中英

如何使用python從列表中選擇特定項目並保存在新列表中

[英]how do I choose specific items from a list using python and save in a new list

我正在用Python(3)編寫一個代碼來檢查產品代碼是否采用某種格式。 代碼作為變量輸入,然后拆分為一個列表。 我有兩個問題。 產品是字母和數字,我希望檢查它們是否符合我的規定安排; 它應該是4個字母1個空格和4個數字然后是2個字母。

下面的代碼似乎工作,但在檢查數據驗證時,似乎.isdigit允許#或其他符號。

我想更優雅,並嘗試使用for循環檢查特定項目是字母,如[0,1,2,3,10,11],但無法理解如何只檢查列表中的這些特定項目

if (len(ProductCode) == 12 and
    ProductCode [0].isalpha and
    ProductCode [1].isalpha and
    ProductCode [3].isalpha and
    ProductCode [4].isalpha  and
    ProductCode [5]== ' ' and
    ProductCode [6].isdigit and
    ProductCode [7].isdigit and
    ProductCode [8].isdigit and
    ProductCode [9].isdigit and
    ProductCode [10].isalpha and
    ProductCode [11].isalpha):
        message = 'Next Product'
else:
    message = 'Non-Standard Product Code'

print(message)

為什么不使用正則表達式:

import re

if re.match('\w{4} \d{4}\w{2}', ProductCode):
    message = 'Next Product'
else:
    message = 'Non-Standard Product Code'

這符合AbcD 1234Az (4個字母數字,空格,4位數和2個字母數字)

因此,如果您只想要字母而不是字母數字,請將模式更改為:

[a-zA-Z]{4} \d{4}[a-zA-Z]{2}

這只是一個如何循環遍歷所需列表的示例,您可以將其應用於您的需求

letters_list = [0,1,2,3,10,11]

def check_letter(ProductCode):
  global letters_list
  for l in letters_list:
    if not ProductCode[l].isalpha: return False
  return True

if check_letter(ProductCode): print("Everything in list is a letter") #define ProductCode 
else: print("Something is wrong")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM