ν”„λ‘œκ·Έλž˜λ° μ–Έμ–΄/Python

[Python] μžλ£Œν˜• - νŠœν”Œ Tuple

NaNaRinπŸ™ƒ 2021. 2. 4. 16:35

0. νŠœν”Œ Tuple μ΄λž€ ?

λ¦¬μŠ€νŠΈμ™€ 거의 λΉ„μŠ·ν•˜μ§€λ§Œ λͺ‡κ°€μ§€ λ‹€λ₯Έ 점이 μ‘΄μž¬ν•œλ‹€.

λ¦¬μŠ€νŠΈλŠ” κ°’μ˜ 생성, μ‚­μ œ, μˆ˜μ •μ΄ κ°€λŠ₯ν•˜μ§€λ§Œ νŠœν”Œμ€ 값을 λ°”κΏ€ 수 μ—†λ‹€

νŠœν”Œμ€ κ΄„ν˜Έ()λ₯Ό μƒλž΅ν•΄λ„ 되기 λ•Œλ¬Έμ— 1개의 μš”μ†Œλ§Œ κ°€μ§ˆ λ•Œμ—λŠ” b=(1,) μ΄λ‚˜ f = 2, 처럼 μš”μ†Œ 뒀에 콀마λ₯Ό λ°˜λ“œμ‹œ λΆ™μ—¬μ•Ό ν•œλ‹€

# νŠœν”Œλͺ… = (μš”μ†Œ1, μš”μ†Œ2, μš”μ†Œ3, …)
# TupleName = (1, 2, 3, …)

a = ()
b = (1,)
c = (1, 2, 3)
d = 1, 2, "this", "Python"
e = ((1, 2), "this", (3, "Python"))
f = 2,

ν”„λ‘œκ·Έλž¨μ΄ μ‹€ν–‰λ˜λŠ” λ™μ•ˆ κ·Έ 값이 λ³€ν•˜μ§€ μ•Šμ•„μ•Ό ν•˜λŠ” 것듀은 νŠœν”Œλ‘œ, μˆ˜μ‹œλ‘œ 값이 λ³€ν•˜λŠ” 것듀은 리슀트둜 μ‚¬μš©

 

1. νŠœν”Œμ˜ 인덱싱

print(b)                            # (1,)
print(b[0])                         # 1
print(c)                            # (1, 2, 3)
print(c[0], c[1], c[2])             # 1 2 3 
print(d)                            # (1, 2, 'this', 'Python')
print(d[0], d[1], d[2], d[3])       # 1 2 this Python
print(e)                            # ((1, 2), 'this', (3, 'Python'))
print(e[0], e[1], e[2])             # (1, 2) this (3, 'Python')
print(e[0][0], e[0][1])             # 1 2
print(e[2][0], e[2][1])             # 3 Python
print(f)                            # (2,)

 

2. νŠœν”Œμ˜ μŠ¬λΌμ΄μ‹±

[a:b] 라면 a <= i < b 의 λ²”μœ„λ§Œ ν¬ν•¨λœλ‹€. 즉, b[0:1]의 경우 b[0]만 좜λ ₯λœλ‹€

print(b[0:1])                       # (1,)
print(c[0:])                        # (1, 2, 3)
print(c[:-1])                       # (1, 2)
print(d[2:])                        # ('this', 'Python')
print(d[:2])                        # (1, 2)
print(e[0:2])                       # ((1, 2), 'this')

 

3. νŠœν”Œμ˜ μ—°μ‚°

+ μ—°μ‚°μž : ν”Όμ—°μ‚°μž νŠœν”Œμ„ ν•©μΉ˜λŠ” κΈ°λŠ₯을 ν•œλ‹€

* μ—°μ‚°μž : ν”Όμ—°μ‚°μž νŠœν”Œμ„ λ°˜λ³΅ν•œλ‹€

f = c + b
print(f)                            # (1, 2, 3, 1)
g = d * 2
print(g)                            # (1, 2, 'this', 'Python', 1, 2, 'this', 'Python')