我有一个物体。id,我试图存储在用户会话作为元组。当我添加第一个时,它可以工作,但tuple看起来像(u'2',),但当我尝试添加一个新的使用mytuple = mytuple + new。Id得到错误只能连接元组(不是"unicode")到元组。
当前回答
从Python 3.5 (PEP 448)开始,你可以在元组、列表集和dict中进行解包:
a = ('2',)
b = 'z'
new = (*a, b)
其他回答
如果逗号让您感到困扰,您可以使用tuple()指定它为元组。
ex_tuple = ('a', 'b')
ex_tuple += tuple('c')
print(ex_tuple)
最重要的是,添加到元组的最简单方法是用圆括号和逗号将添加的元素括起来。
t = ('a', 4, 'string')
t = t + (5.0,)
print(t)
out: ('a', 4, 'string', 5.0)
Tuple只允许向它添加Tuple。最好的方法是:
mytuple =(u'2',)
mytuple +=(new.id,)
我用下面的数据尝试了相同的场景,它似乎都工作得很好。
>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
你需要使第二个元素为1元组,例如:
a = ('2',)
b = 'z'
new = a + (b,)
tup = (23, 2, 4, 5, 6, 8)
n_tup = tuple(map(lambda x: x+3, tup))
print(n_tup)