我这里有一个电话号码,可以说:98888888xx
最后两个XX
是我要生成类似988888811
,9888888812
,{ {1}},依此类推。
我正在尝试学习python编程,所以有人可以帮助我如何继续编写相同的脚本
答案 0 :(得分:0)
您可以使用list comprehension
和range()
:
['98888888' + str(number).zfill(2) for number in range(100)]
['9888888800',
'9888888801',
'9888888802',
...
'9888888897',
'9888888898',
'9888888899']
答案 1 :(得分:0)
一个可靠的解决方案是使用递归来处理"x"
的许多可能出现的情况:
import re
s = '98888888xx'
_len = len(re.sub('\d+', '', s))
def combos(d, current = []):
if len(current) == _len:
yield current
else:
for i in d[0]:
yield from combos(d[1:], current+[i])
_c = combos([range(1, 10)]*_len)
new_result = [(lambda d:re.sub('x', lambda _:str(next(d)), s))(iter(i)) for i in _c]
输出:
['9888888811', '9888888812', '9888888813', '9888888814', '9888888815', '9888888816', '9888888817', '9888888818', '9888888819', '9888888821', '9888888822', '9888888823', '9888888824', '9888888825', '9888888826', '9888888827', '9888888828', '9888888829', '9888888831', '9888888832', '9888888833', '9888888834', '9888888835', '9888888836', '9888888837', '9888888838', '9888888839', '9888888841', '9888888842', '9888888843', '9888888844', '9888888845', '9888888846', '9888888847', '9888888848', '9888888849', '9888888851', '9888888852', '9888888853', '9888888854', '9888888855', '9888888856', '9888888857', '9888888858', '9888888859', '9888888861', '9888888862', '9888888863', '9888888864', '9888888865', '9888888866', '9888888867', '9888888868', '9888888869', '9888888871', '9888888872', '9888888873', '9888888874', '9888888875', '9888888876', '9888888877', '9888888878', '9888888879', '9888888881', '9888888882', '9888888883', '9888888884', '9888888885', '9888888886', '9888888887', '9888888888', '9888888889', '9888888891', '9888888892', '9888888893', '9888888894', '9888888895', '9888888896', '9888888897', '9888888898', '9888888899']
请注意,只有两个'x'
时,会以嵌套列表理解的形式出现一个简单的解决方案:
d = [s.replace('x', '{}').format(a, b) for a in range(1, 10) for b in range(1, 10)]
但是,当输入字符串包含三个或更多'x'
时,多个嵌套循环并不是解决问题的一种干净方法。相反,递归效果最好:
s = '98888888xxxxx'
_len = len(re.sub('\d+', '', s))
_c = combos([range(1, 10)]*_len)
new_result = [(lambda d:re.sub('x', lambda _:str(next(d)), s))(iter(i)) for i in _c]
输出(前二十个字符串):
['9888888811111', '9888888811112', '9888888811113', '9888888811114', '9888888811115', '9888888811116', '9888888811117', '9888888811118', '9888888811119', '9888888811121', '9888888811122', '9888888811123', '9888888811124', '9888888811125', '9888888811126', '9888888811127', '9888888811128', '9888888811129', '9888888811131', '9888888811132']