我知道我无法修改元组,并且我已经看到了从另一个元素创建元组的手段,如here手动连接部分元组。生成元组的修改后的副本
但想知道是否已经出现了一些Python的方式来通过隐含创建一个新的像
>>> source_tuple = ('this', 'is', 'the', 'old', 'tuple')
>>> new_tuple = source_tuple.replace(3, 'new')
>>> new_tuple
('this', 'is', 'the', 'new', 'tuple')
一个可能的实现看起来是这样的“修改”一个元组,但我正在寻找建立在一个解决方案:
def replace_at(source, index, value):
if isinstance(source, tuple):
return source[:index] + (value,) + source[index + 1:]
elif isinstance(source, list):
return source[:index] + [value,] + source[index + 1:]
else:
explode()
它没有太多的工作来实现这样的功能,但像Enum
已经证明它有时最好能有一个实现每个人都使用..我的目标是而不是替换源元组。我知道我可以使用列表,但即使在这种情况下,我也会先制作一个副本。所以我真的只是寻找一种方法来创建一个修改后的副本。
这就是列表... – wim
'tuple(u''.join(source_tuple).replace('old','new')。split(u''))' – wim