Answers:
您需要将第二个元素设为1元组,例如:
a = ('2',)
b = 'z'
new = a + (b,)
(a+b)*c
new = a + b
代替new = a + (b,)
。AFAICT在python3和python2.7中的工作原理相同。
a += ('z',)
,如波纹管回答中所述
从元组到列表再到元组:
a = ('2',)
b = 'b'
l = list(a)
l.append(b)
tuple(l)
或附有较长的项目清单
a = ('2',)
items = ['o', 'k', 'd', 'o']
l = list(a)
for x in items:
l.append(x)
print tuple(l)
给你
>>>
('2', 'o', 'k', 'd', 'o')
这里的重点是:列表是可变的序列类型。因此,您可以通过添加或删除元素来更改给定列表。元组是不可变的序列类型。您不能更改元组。因此,您必须创建一个新的。
list
,请追加项目,然后在最后转换为,tuple
那么这是最佳的解决方案+1
>>> x = (u'2',)
>>> x += u"random string"
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", ) # concatenate a one-tuple instead
>>> x
(u'2', u'random string')
a = ('x', 'y')
b = a + ('z',)
print(b)
a = ('x', 'y')
b = a + tuple('b')
print(b)
TypeError: 'int' object is not iterable