Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换列表中的元素_Python - Fatal编程技术网

Python 替换列表中的元素

Python 替换列表中的元素,python,Python,我试图替换列表中的元素 # the raw data square = ['(', ')', '.', '^', '-'] # the result I want square = ['[', ']', '.', '^', '-'] 使用删除和插入 In [21]: square.remove('(') In [22]: square.remove(')') In [23]: square.insert(0, '[') In [24]: square.inse

我试图替换列表中的元素

# the raw data 
square = ['(', ')', '.', '^', '-']
# the result I want
square = ['[', ']', '.', '^', '-']
使用
删除
插入

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

如何以严格的方式解决此问题?

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

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

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

print square

>>> ['[', ']', '.', '^', '-']
另一方面,如果您不确定括号在列表中的位置,可以使用enumerate()并在单个循环中访问循环元素的索引和值:

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

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

print square

>>> ['[', ']', '.', '^', '-']
在我看来,这些是最直接的方法

如果我可以建议的话,下一步是使用列表(和/或字典)理解,更具python风格


查看Daniel Roseman答案中的宝石,了解答案。

字典对这类事情非常有用。使用列表理解在替换字典中迭代并查找每个元素,使用
.get
,使其默认为当前项

replacements = {'(': '{', ')': '}'}
square = [replacements.get(elem, elem) for elem in square]
使用re模块:

import re

print(list(re.sub(r'\(\)','\[\]',''.join(square))))
>>>['[', ']', '.', '^', '-']
可能重复的
import re

print(list(re.sub(r'\(\)','\[\]',''.join(square))))
>>>['[', ']', '.', '^', '-']