[英]How to replace strings which match a regex pattern?
我有数字清单。 我想提取具有连续数字的所有数字,例如444,888,1111等。我下面的带有regex的python代码正在按照我想要的方式工作。
import re
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567', '555', '99999', '11211','11']
conList = []
for num in numbers:
if re.search(r'^(\d)\1+$',num):
conList.append(num)
print('conList :',conList)
结果:
conList : ['44444', '444', '888', '1111', '3333', '555', '99999', '11']
现在,我尝试不使用正则表达式模式来达到相同的结果。 如何用某些python代码替换该正则表达式模式? (我仅出于教育目的尝试此操作。如果得到答案,我将发布答案。)
这是我解决这个问题的尝试。
for num in numbers:
if len(set(num)) == 1 and len(num) >1:
conList.append(num)
print('conList :',conList)
或者,使用列表理解
conList = [ num for num in numbers if len(num) > 1 and len(set(num)) == 1 ]
print('conList : %s', conList)
或者,使用过滤器
conList = filter(lambda x: len(x) > 1 and len(set(x)) == 1, numbers)
使用pythonic和快速的列表理解方法:
[i for i in numbers if len(set(i)) == 1]
您可以使用列表推导功能如下一行完成此操作:
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567',
'555', '99999', '11211', '11']
conList = [x for x in numbers if x.count(x[0]) == len(x)]
print conList
输出:
['44444', '444', '888', '1111', '3333', '555', '99999', '11']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.