【发布时间】:2023-01-31 00:09:19
【问题描述】:
我正在尝试在 python (googlecollab) 中使用条件练习正则表达式模式,但通过从列表 [000 到 999] 中获取正确的数字而陷入(如果...和...) - 我只需要数字,以一个结尾数字“1”(不是 11、111、211 - 我只需要 001、021、031、101),但它在多个条件下不返回任何内容...如果我清除条件中以“和”开头的代码 - 它返回所有, 十一, 一百十一...
list_ = []
list_.append('000')
for a in range(999):
list_.append(str(a+1))
for i, el in enumerate(list_):
if len(el) == 1:
list_[i] = '00'+el
elif len(el) == 2:
list_[i] = '0'+el
for item in list_:
try:
if item == re.match(r'\d\d1', item).group() \
and item != re.match(r'\d11', item).group():
print(item)
except:
pass
【问题讨论】:
-
旁注:您的列表生成代码可以简化为
list_ = [str(x).zfill(3) for x in range(1000)] -
您可以使用 $ 在字符串末尾查找 1。另外,我不会将您的
item与匹配项进行比较,而是检查匹配项是否为非空。 -
您可以将前四行(生成
list_)简化为list_ = [str(i).zfill(3) for i in range(1000)]
标签: python if-statement design-patterns match python-re