[英]how do I choose specific items from a list using python and save in a new list
I am writing a code in Python (3) that checks a product code is in a certain format. 我正在用Python(3)编写一个代码来检查产品代码是否采用某种格式。 the codes are entered as a variable and then split into a list. 代码作为变量输入,然后拆分为一个列表。 I have two issues. 我有两个问题。 The products are both letters and numbers and I wish to check they conform to my prescribed arrangement; 产品是字母和数字,我希望检查它们是否符合我的规定安排; it should be 4 letters 1 space and 4 numbers then 2 letters . 它应该是4个字母1个空格和4个数字然后是2个字母。
The code below seems to work but when checking data validation it appears that .isdigit allows # or other symbols. 下面的代码似乎工作,但在检查数据验证时,似乎.isdigit允许#或其他符号。
I want to make more elegant and try and use a for loop to check specific items are letters eg [0,1,2,3,10,11] but cannot understand how to only check these specific items in the list 我想更优雅,并尝试使用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)
Why not use a regular expression: 为什么不使用正则表达式:
import re
if re.match('\w{4} \d{4}\w{2}', ProductCode):
message = 'Next Product'
else:
message = 'Non-Standard Product Code'
This matches something like AbcD 1234Az
(4 alphanumeric, space, 4 digits and 2 alphanumerics) 这符合AbcD 1234Az
(4个字母数字,空格,4位数和2个字母数字)
So if you only want letters instead of the alphanumerics, change the pattern to: 因此,如果您只想要字母而不是字母数字,请将模式更改为:
[a-zA-Z]{4} \d{4}[a-zA-Z]{2}
This is Just an example of how you can loop through the list you want, you can apply it to your needs 这只是一个如何循环遍历所需列表的示例,您可以将其应用于您的需求
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.