如何使用python从列表中选择特定项并保存在新的lis中

2024-04-25 17:53:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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)

Tags: and项目代码message列表产品格式字母
2条回答

为什么不使用正则表达式:

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")

相关问题 更多 >