[英]How do I create a new list with specific items from an old list in Python 2?
[英]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.