Python 向元组添加项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16730339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:27:57  来源:igfitidea点击:

Python add item to the tuple

pythonpython-2.7tuples

提问by Goran

I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like (u'2',)but when I try to add new one using mytuple = mytuple + new.idgot error can only concatenate tuple (not "unicode") to tuple.

我有一些 object.ID-s,我尝试将其作为元组存储在用户会话中。当我添加第一个时,它可以工作,但元组看起来像,(u'2',)但是当我尝试使用mytuple = mytuple + new.idgot error添加新的时can only concatenate tuple (not "unicode") to tuple

采纳答案by Jon Clements

You need to make the second element a 1-tuple, eg:

您需要将第二个元素设为 1 元组,例如:

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

回答by jamylak

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

回答by kiriloff

From tuple to list to tuple :

从元组到列表再到元组:

a = ('2',)
b = 'b'

l = list(a)
l.append(b)

tuple(l)

Or with a longer list of items to append

或者使用更长的项目列表来附加

a = ('2',)
items = ['o', 'k', 'd', 'o']

l = list(a)

for x in items:
    l.append(x)

print tuple(l)

gives you

给你

>>> 
('2', 'o', 'k', 'd', 'o')

The point here is: List is a mutablesequence type. So you can change a given list by adding or removing elements. Tuple is an immutablesequence type. You can't change a tuple. So you have to create a newone.

这里的要点是:List 是一种可变序列类型。因此,您可以通过添加或删除元素来更改给定列表。元组是一种不可变的序列类型。你不能改变元组。所以你必须创建一个新的

回答by user3798348

Tuple can only allow adding tupleto it. The best way to do it is:

元组只能允许添加tuple到它。最好的方法是:

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

I tried the same scenario with the below data it all seems to be working fine.

我用下面的数据尝试了相同的场景,它似乎一切正常。

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')

回答by nitely

Since Python 3.5 (PEP 448) you can do unpacking within a tuple, list set, and dict:

从 Python 3.5 ( PEP 448) 开始,您可以在元组、列表集和字典中进行解包:

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

回答by britodfbr

#1 form

#1 表格

a = ('x', 'y')
b = a + ('z',)
print(b)

#2 form

#2 形式

a = ('x', 'y')
b = a + tuple('b')
print(b)

回答by alphahmed

Bottom line, the easiest way to append to a tuple is to enclose the element being added with parentheses and a comma.

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

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

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