2016-09-21 39 views
1

我知道我无法修改元组,并且我已经看到了从另一个元素创建元组的手段,如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已经证明它有时最好能有一个实现每个人都使用..我的目标是而不是替换源元组。我知道我可以使用列表,但即使在这种情况下,我也会先制作一个副本。所以我真的只是寻找一种方法来创建一个修改后的副本。

+3

这就是列表... – wim

+0

'tuple(u''.join(source_tuple).replace('old','new')。split(u''))' – wim

回答

2

您可以在元组(这将产生一个新的元组)使用切片并连接:

>>> x=3 
>>> new_tuple=source_tuple[0:x]+('new',)+source_tuple[x+1:] 
>>> new_tuple 
('this', 'is', 'the', 'new', 'tuple') 

然后你就可以支持任何一个列表或元组,像这样:

>>> def replace_at(source, index, value): 
...  return source[0:index]+type(source)((value,))+source[index+1:] 
... 
>>> replace_at([1,2,3],1,'new') 
[1, 'new', 3] 
>>> replace_at((1,2,3),1,'new') 
(1, 'new', 3) 

或者,只是做它直接在列表上:

>>> source_tuple = ('this', 'is', 'the', 'old', 'tuple') 
>>> li=list(source_tuple) 
>>> li[3]='new' 
>>> new_tuple=tuple(li) 
>>> new_tuple 
('this', 'is', 'the', 'new', 'tuple') 

正如评论指出 - 这就是名单是...

+0

你可以这样做当然,但你必须承认,这段代码既不简短也不直观,因为它是三行代码,两行代码只是说“用新元素替换元素3” – frans

+0

尝试切片然后:'new_tuple = source_tuple [0:3 ] +('new',)+ source_tuple [4:]' – dawg

+0

这是我写的:) – frans

0

你可以使用某种理解:

source_tuple = ('this', 'is', 'the', 'old', 'tuple') 
new_tuple = tuple((value if x != 3 else 'new' 
        for x, value in enumerate(source_tuple))) 
# ('this', 'is', 'the', 'new', 'tuple') 

这是在这种情况下,而idotic但给你的一般概念的想法。尽管如此,更好地使用列表,但毕竟,您可以在此处更改基于索引的值。

0

如果你需要创建替换元素新的记录,你可以使用这样的事情:

def replace_value_in_tuple(t, ind, value): 
    return tuple(
     map(lambda i: value if i == ind else t[i], range(len(t))) 
    ) 
1

如果你想在交换价值飞,那么list是比较合适的数据结构;因为我们已经知道元组是不可变的

在另一方面,如果你在一个tuple寻找交换价值的逻辑,你可以看看collections.namedtuple具有_replace方法。

只要定期元组使用

>>> source_tuple = ('this', 'is', 'the', 'old', 'tuple') 

>>> Factory = namedtuple('Factory', range(5), rename=True) 

>>> source_tuple = Factory(*source_tuple) 

>>> source_tuple 
Factory(_0='this', _1='is', _2='the', _3='old', _4='tuple') 

>>> new_tuple = source_tuple._replace(_3='new') 

>>> new_tuple 
Factory(_0='this', _1='is', _2='the', _3='new', _4='tuple') 

嗯,这看上去并不是很优雅,他们都可以使用。我仍然建议您改用list