Gor*_*ran 141 python tuples python-2.7
我有一些object.ID-s,我尝试将其作为元组存储在用户会话中.当我添加第一个它工作,但元组看起来像(u'2',)
,但当我尝试使用获取mytuple = mytuple + new.id
错误添加新的can only concatenate tuple (not "unicode") to tuple
.
Jon*_*nts 266
您需要将第二个元素设为1元组,例如:
a = ('2',)
b = 'z'
new = a + (b,)
Run Code Online (Sandbox Code Playgroud)
nit*_*ely 46
从Python 3.5(PEP 448)开始,您可以在元组,列表集和字典中进行解包:
a = ('2',)
b = 'z'
new = (*a, b)
Run Code Online (Sandbox Code Playgroud)
kir*_*off 32
从元组到列表到元组:
a = ('2',)
b = 'b'
l = list(a)
l.append(b)
tuple(l)
Run Code Online (Sandbox Code Playgroud)
或者使用更长的要追加的项目列表
a = ('2',)
items = ['o', 'k', 'd', 'o']
l = list(a)
for x in items:
l.append(x)
print tuple(l)
Run Code Online (Sandbox Code Playgroud)
给你
>>>
('2', 'o', 'k', 'd', 'o')
Run Code Online (Sandbox Code Playgroud)
这里的要点是:List是一个可变序列类型.因此,您可以通过添加或删除元素来更改给定列表.元组是一种不可变的序列类型.你不能改变一个元组.所以你必须创建一个新的.
小智 12
元组只能允许添加tuple
它.最好的方法是:
mytuple =(u'2',)
mytuple +=(new.id,)
Run Code Online (Sandbox Code Playgroud)
我用下面的数据尝试了相同的场景,它似乎都运行良好.
>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
Run Code Online (Sandbox Code Playgroud)
jam*_*lak 11
>>> 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')
Run Code Online (Sandbox Code Playgroud)
小智 9
a = ('x', 'y')
b = a + ('z',)
print(b)
Run Code Online (Sandbox Code Playgroud)
a = ('x', 'y')
b = a + tuple('b')
print(b)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
308832 次 |
最近记录: |