[英]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.