programing

Python이 튜플에 항목 추가

goodcopy 2022. 10. 27. 22:17
반응형

Python이 튜플에 항목 추가

나는 어떤 목적이 있다.사용자 세션에 태플로 저장하려고 하는 ID.첫 번째 것을 추가하면 동작하지만 태플은(u'2',)새로운 것을 추가하려고 하면mytuple = mytuple + new.id에러가 발생했습니다.can only concatenate tuple (not "unicode") to tuple.

두 번째 요소를 1-태플로 만들어야 합니다.다음은 예를 제시하겠습니다.

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

Python 3.5(PEP 448)에서는 탭, 목록 세트 및 dict 내에서 압축을 풀 수 있습니다.

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

tuple에서 list로 tuple로 :

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

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

tuple(l)

또는 추가할 항목 목록이 더 길거나

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

l = list(a)

for x in items:
    l.append(x)

print tuple(l)

주다

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

요점은 리스트는 가변 시퀀스 타입이라는 것입니다.따라서 요소를 추가하거나 제거하여 특정 목록을 변경할 수 있습니다.태플은 불변의 시퀀스 타입입니다.태플은 바꿀 수 없어요.그래서 새로 만들어야 합니다.

태플은 추가만 허용합니다.tuple가장 좋은 방법은 다음과 같습니다.

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

아래 데이터로 같은 시나리오를 써봤는데 잘 되는 것 같아요.

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
>>> 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')

#1 폼

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

#2 폼

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

요컨대, 태플에 추가하는 가장 쉬운 방법은 추가할 요소를 괄호와 쉼표로 둘러싸는 것입니다.

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

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

언급URL : https://stackoverflow.com/questions/16730339/python-add-item-to-the-tuple

반응형