将数字与Word分开并在Python中返回新列表

时间:2018-07-09 18:33:08

标签: python string concatenation

new_list = []
pattern = re.compile("([0-9]+)([a-zA-Z]+)")

for i, x in enumerate(my_list):
    if (re.match(r"([0-9]+)([a-zA-Z]+)", x)):
        result = pattern.match(x)
        #result = result.group(1) + ' ' + result.group(2)
        new_list.append(result.group(1))
        new_list.append(result.group(2))
        i = i + 2
        new_list = new_list + my_list[i:]

return new_list

当前输出:

Input: ['2fee', 'lmao', '222wow']

Output: ['2', 'fee', '222', '222wow', '222', 'wow']

所需的输出:

['2', 'fee', 'lmao', '222', 'wow']

如何获得此输出?非常感谢

2 个答案:

答案 0 :(得分:2)

itertools.groupbystr.isdigit一起使用:

from itertools import groupby

L = ['2fee', 'lmao', '222wow']

res = [''.join(j) for strng in L for _, j in groupby(strng, key=str.isdigit)]

# ['2', 'fee', 'lmao', '222', 'wow']

请注意,这将拆分出现在字符串中的每个数字实例。例如,'1a23bc'将被拆分为'1''a''23''bc'

答案 1 :(得分:1)

或者,尝试:

import re
input = ['2fee', 'lmao', '222wow']
output = []
for s in input:
    output.extend(t for t in re.split('(\d+)', s) if t)
print output