我有一个物体。id,我试图存储在用户会话作为元组。当我添加第一个时,它可以工作,但tuple看起来像(u'2',),但当我尝试添加一个新的使用mytuple = mytuple + new。Id得到错误只能连接元组(不是"unicode")到元组。


当前回答

>>> 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')

其他回答

如果逗号让您感到困扰,您可以使用tuple()指定它为元组。

ex_tuple = ('a', 'b')
ex_tuple += tuple('c')
print(ex_tuple)

从元组到列表到元组:

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是一种不可变序列类型。你不能改变元组。所以你必须创建一个新的。

>>> 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')

最重要的是,添加到元组的最简单方法是用圆括号和逗号将添加的元素括起来。

t = ('a', 4, 'string')
t = t + (5.0,)
print(t)

out: ('a', 4, 'string', 5.0)

你需要使第二个元素为1元组,例如:

a = ('2',)
b = 'z'
new = a + (b,)