列表中的替换元素

Alg*_*bra 3 python

我试图替换列表中的元素

# the raw data 
square = ['(', ')', '.', '^', '-']
# the result I want
square = ['[', ']', '.', '^', '-']
Run Code Online (Sandbox Code Playgroud)

使用remove和的方法的多个步骤insert

    In [21]: square.remove('(')
    In [22]: square.remove(')')
    In [23]: square.insert(0, '[')
    In [24]: square.insert(1, ']')
    In [25]: square
    Out[25]: ['[', ']', '.', '^', '-']
Run Code Online (Sandbox Code Playgroud)

如何以一种直截了当的方式解决这样的问题?

Dan*_*man 11

字典对于这种事情很有用.使用列表推导来迭代并查找替换字典中的每个元素.get,使其默认为当前项.

replacements = {'(': '{', ')': '}'}
square = [replacements.get(elem, elem) for elem in square]
Run Code Online (Sandbox Code Playgroud)


Pit*_*tto 5

最简单的解决方案是,如果您准确知道要更改的元素的索引,则使用列表索引:

square = ['(', ')', '.', '^', '-']

square[0] = '['
square[1] = ']'

print square

>>> ['[', ']', '.', '^', '-']
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您不确定括号在列表中的位置,可以使用enumerate(),并且在单个循环中,您将能够访问循环元素的索引和值:

square = ['(', ')', '.', '^', '-']

for index, element in enumerate(square):
    if element == '(':
        square[index] = '['
    if element == ')':
        square[index] = ']'

print square

>>> ['[', ']', '.', '^', '-']
Run Code Online (Sandbox Code Playgroud)

在我看来,这些是最直接的方式.

如果我可以建议,下一步是使用列表(和/或词典)理解更多Pythonic.

检查Daniel Roseman的答案中的宝石,以获得一个想法.