我有一个物体。id,我试图存储在用户会话作为元组。当我添加第一个时,它可以工作,但tuple看起来像(u'2',),但当我尝试添加一个新的使用mytuple = mytuple + new。Id得到错误只能连接元组(不是"unicode")到元组。
当前回答
我最喜欢的:
myTuple = tuple(list(myTuple).append(newItem))
是的,我知道它很贵,但它看起来确实很酷:)
其他回答
>>> 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只允许向它添加Tuple。最好的方法是:
mytuple =(u'2',)
mytuple +=(new.id,)
我用下面的数据尝试了相同的场景,它似乎都工作得很好。
>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
如果逗号让您感到困扰,您可以使用tuple()指定它为元组。
ex_tuple = ('a', 'b')
ex_tuple += tuple('c')
print(ex_tuple)
你需要使第二个元素为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)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录