Python

[Python] tuple

언킴 2021. 6. 25. 22:36
반응형

tuple의 형태와 기초를 다루는 형태로 코드를 작성해보았다.

# tuple
t1 = ()

t2 = (1,)

t3 = (1, 2, 3)

# 괄호를 생략해도 무방
t4 = 1, 2, 3

t5 = ('a', 'b', ('ab', 'cd'))

t1, t2, t3, t4, t5

# list 의 값은 변경이 가능하지만 tuple의 값은 변경이 불가능하다.

# 지우는 것이 불가능
t1 = 1, 2, 'a', 'b'

del t1[0] # error

# 변경 불가능
t1[0] = 'c' # error

# indexing
t1 = 1, 2, 'a', 'b'

t1[0] # 1

a = ((1 ,2) , (3,4), (5,9))

a[:][1] # (3, 4)

# slicing
t1[:-1] # (1, 2, 'a')

t1[1:-1] # (2, 'a')

a[0][:] # (1, 2)

a[:-1][:] # ((1, 2), (3, 4))

# add
t2 = (3,4)

t1 + t2 # (1, 2, 'a', 'b', 3, 4)

# multiple
t2 * 3 # (3, 4, 3, 4, 3, 4)

t1 * 3 # (1, 2, 'a', 'b', 1, 2, 'a', 'b', 1, 2, 'a', 'b')

# length of tuple
len(t1)

# type
type(t1) # <class 'tuple'>

# ,를 해주지 않으면 tuple 형태가 되지 않는다.
h1 = (150)
type(h1) # <class 'int'>

h2 = (150,) 
type(h2) # <class 'tuple'>

packing을 해서 format으로 대입시켰다.

# tuple packing
information = '홍길동', 'cs', 'Seoul', 4
name, major, live, family = information
print('name : {0}, major : {1}, live : {2}, family : {3} '.format(name, major, live, family))

# name : 홍길동, major : cs, live : Seoul, family : 4

 

# for

for i in t1:
    print(i)

# while
t1
i = 0
n = 0
while i <=5:
    for j in t1: # len(t1) == 4
        print(j)
        n += 1
    i += 1
print('{0:.4f}'.format(i)) # 6
print('%.4f' %n ) # 24 \d : int, \f : float, \s : string,  %o : 8진수, %x : 16진수
# 출력값을 tuple로 반환할 수 있다.
h = [7,5,2,1,11,15,55]
def minmax(tuple):
    return min(tuple), max(tuple)

minmax(h)



# a가 하나라도 포함되어 있으면 출력한다.
q1 = ('a', 'b', 'e','ad','ef','aaa','aa','eead')
count = 0
a_list = []
for i in q1:
    if 'a' in i:
        a_list.append(i)
        count += 1
    else:
        print('not include a : ', i)
print(f'count : {count}')
print(a_list)


# a_list 안에 있는 a를 count
result = []
for index in a_list:
    if len(index) != 1:
        for j in index:
            result.append(j)
result.count('a')

'Python' 카테고리의 다른 글

[Python] ConnectionResetError (request)  (0) 2022.04.27
[python] os, os.path로 파이썬 경로 다루기  (0) 2022.04.01
request <Response [401]>  (0) 2022.03.11
[Python] Class  (0) 2022.01.14
[Python] Open file  (0) 2021.09.30