203

ユーザーセッションにタプルとして保存しようとするobject.ID-sがいくつかあります。最初のものを追加すると機能しますが、タプルは次のように見えますが、 got error(u'2',)を使用して新しいものを追加しようとすると。mytuple = mytuple + new.idcan only concatenate tuple (not "unicode") to tuple

4

7 に答える 7

367

2 番目の要素を 1 タプルにする必要があります。

a = ('2',)
b = 'z'
new = a + (b,)
于 2013-05-24T08:05:52.840 に答える
83

Python 3.5 ( PEP 448 ) 以降、タプル、リスト セット、および辞書内でアンパックを実行できます。

a = ('2',)
b = 'z'
new = (*a, b)
于 2016-08-28T15:56:00.923 に答える
16

タプルは追加のみを許可できtupleます。それを行う最良の方法は次のとおりです。

mytuple =(u'2',)
mytuple +=(new.id,)

以下のデータで同じシナリオを試してみましたが、すべて正常に動作しているようです。

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
于 2014-07-02T15:25:34.817 に答える
12
>>> 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')
于 2013-05-24T08:05:53.433 に答える