PYTHON:使用正则表达式的多次替换

时间:2016-06-20 07:46:45

标签: python regex string

我有来自db类型的列表:

[[63], [426], [255], [167], [648], [364, 194], [686, 14]]  

我想将它们转换为:

63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 14 -1 -2  and newline

,即如果多个元素使用"空格"则在内部列表中分开。主要列表中的元素和使用" -1"最后a" -2"必须存在换行符 结果条目必须是数字 任何想法(最好使用正则表达式)? 谢谢!

3 个答案:

答案 0 :(得分:0)

UPDATE:处理嵌套列表的解决方案:

final_list = []
my_list = [[63], [426], [255], [167], [648], [364, 194], [686, [7, 77, 777], 14]]

def recursive_convert(item):
    if type(item) is list:
        for i in item:
            recursive_convert(i)
    else:
        final_list.append(item)

for sublist in my_list:
    recursive_convert(sublist)
    final_list.append(-1)

final_list.append(-2)
final_list.append('\n')

t = ' '.join(map(str, final_list))
print(t)

输出:

 xclip -o > k2.py                                                                                                                                                         
 python3 k2.py     
63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 7 77 777 14 -1 -2 \n

在嵌套子列表之前和之后没有-1,因为OP说他希望只插入-1来展示“主列表”的中断。

没有嵌套列表的解决方案:

final_list = []
my_list = [[63], [426], [255], [167], [648], [364, 194], [686, 14]]

for sublist in my_list:
    for item in sublist:
        final_list.append(item)
    final_list.append(-1)

final_list += [-2, '\n']
' '.join(map(str, final_list))

输出:

63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 14 -1 -2 \n

答案 1 :(得分:0)

你可以试试这个:

array = [[63], [426], [255], [167], [648], [364, 194], [686, 14]]

out = ''

for group in array:
    for elt in group:
        out += str(elt) + ' '

    out += '-1 '

out += '-2 \n'

print(out)

哪个输出:

63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 14 -1 -2 [newline]

你不需要在这里使用正则表达式,这甚至是一个坏主意,因为你正在处理列表。

希望它会有所帮助。

答案 2 :(得分:0)

采取"客户永远是对的"方法,尽管它是错误解决问题的方法,我们可以用正则表达式和字符串操作做一些事情。要处理任意列表深度,您还需要包含您最喜欢的压扁例程的实现:

import re

def flatten(array):
    new_array = []

    for element in array:
        if isinstance(element, int):
            new_array.append(element)
        else:
            new_array.extend(flatten(element))

    return new_array

array = [[63], [426], [255], [167], [648], [364, 194], [686, [7, 77, 777], 14]]

string = re.sub(r'[,\[]', '', str(list(map(flatten, array)))).replace('] ', ' -1 ').replace(']]', ' -1 -2\n')

print(string, end='')

产生:

  

63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 7 77 777 14 -1 -2

相关问题