2

我发现使用正则表达式我可以得到修改后的字符串而不必显式循环原始字符串,这很酷——例如在 Python 中:

from re import sub
print sub(r'12', r'twelve', r'12 + 12 = 24')

印刷

twelve + twelve = 24

一般来说,列表有类似的东西吗?特别是,它如何在 Python 中使用将是最受赞赏的,但在任何语言中这样的东西也会很酷。

我可能拥有的示例任务会得到一个类似的列表

[0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1]

替换所有出现的0 , 12以便我得到:

[0, 2, 1, 2, 2, 1, 2]

当然,在这种特殊情况下,我可以将列表转换为一串数字,然后使用正则表达式,但我希望有一些我可以使用的模拟列表。

4

2 回答 2

2

There does not seem to be a regex analog for list operations. For some simple cases like yours , you can do this :

  1. You can convert the list to str
  2. use regex replace to replace elements as per your requirement.
  3. use literal_eval to convert the modified string to list again.

Working here : http://ideone.com/tgg3N

from re import sub
import ast

myList = [0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1]
listStr = str(myList)
myNewStr = sub(r'0\s*,\s*1',r'2',listStr)
myNewList = ast.literal_eval(myNewStr)
print str(myNewList)

But that is not a good way to do it when you can logically do all the operations on the list by replacing elements from the list instead of doing a regex replace on its string representation .

于 2012-08-17T07:35:24.177 回答
2

对于这个单一的案例:

a = [0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1]
b = []

while a:
    x = a.pop(0)
    if x == 0 and a and a[0] == 1:
        a.pop(0)
        b.append(2)
    else:
        b.append(x)
于 2012-08-17T07:08:18.740 回答