Python문법_2

coh·2022년 5월 18일
0

python

목록 보기
2/8

Tuple

tuple은 immutable한 자료형이에요.

b = tuple('abc')
b = tuple([1,2,3])
b = 4, 5
a=1, 2, 3
a[0]
a[:2]

각 object들을 tuple object로 convert할 수 있고
그냥 comma연산자로 보내면 tuple로 처리해 줍니다.
마찬가지로 index와 slicing도 활용할 수 있습니다.

그렇다면 왜 tuple을 쓸까요? list 하나면 되는 거 아닌가?

프로그램의 강건성 때문에

Sometimes we don't want data to be modified.
Dictionary requires an immutable type as its keys
Program execution is faster when using a tuple than it is for the equivalent list.

A tuple is immutable, but it can contain mutable objects.

a = ([1,2], [3,4])
a[0] = 1 
#Error
a[0][0] = 5
#Possible!!

list 는 mutable하기 때문에 tuple 내의 list를 수정하는 것은 가능합니다!

Iterable objects

An object capable of returning its members one at a time.
Iterable objects can be used in for loops, and map() function.
string, list, tuple, dictionary, set, range 모두 iterable 한 object이다.

for i in [1,2,3,4]:
	print(i, end = ' ')

in operator는 iterable한 object에서 인자를 하나씩 꺼내서 assign해주는 역할을 한다. 출력할 때 end를 지정하지 않으면 python print함수는 자동적으로 개행을 넣어서 출력한다. 나는 ' ' space로 출력을 지정했다.

range

range() function returns a range object, which is a sequence of numbers.
The range object is immutable and iterable.

>>> a = range(5)
>>> type(a)
<class 'range'>
>>> list(a)
[0, 1, 2, 3, 4]
>>> tuple(a)
(0, 1, 2, 3, 4)
>>> for i in range(1,5):
	print(i, end = '*')

	
1*2*3*4*

>>> for i in range(1, -4, -1):
	print(i, end=' ')

	
1 0 -1 -2 -3 
>>> 

아 이거 복사가 되는구나.. 지금 처음 알았다. ㅋㅋㅋㅋㅋ
나 바본가보다. 지금까지 일일이 다 쳤는데...

string

string을 다루는 것이 너무너무 중요하기 때문에 좀더 깊게 짚고 넘어갈게요.

>>> data = "Hello! coh!"
>>> data[1]
'e'
>>> data[1:4]
'ell'
>>> a = data.lower()
>>> b = data.upper()
>>> a, b
('hello! coh!', 'HELLO! COH!')
>>> data ='123'
>>> data.isnumeric()
True
>>> data = "have a nice day!"
>>> data.split()
['have', 'a', 'nice', 'day!']
>>> data = data.split()
>>> one = '*'.join(data)
>>> print(one)
have*a*nice*day!
>>> one
'have*a*nice*day!'

string 내장함수인 lower(), upper(), isnumeric(), split(), join()함수의 사용법을 살펴보았어요.
isnumeric()은 문자열의 모든 문자가 숫자에 해당하는 character일 때 true입니다.
split()은 white space를 기준으로 string을 나눠서 list에 저장해 주는 함수입니다.
join함수는 parameter를 현재 object의 string을 포함시켜 하나의 string으로 만들어주는 함수입니다!

한 가지 설명하고 넘어가야 하는 부분은 anonymous objects이다. 즉, 이름이 없는 object를 의미한다.
data[1] or data[1:4] code를 실행하면 reference variable로 지정되지 않은 object가 생성한다.
anonymous objects들이 이렇게 수없이 많이 생성되면 메모리 공간은..?
이를 해결하기 위해 python에서는 자동적으로 garbage collection을 해줘서 이러한 objects를 자체적으로 날려버린다.

여담인데,
c++같은 경우 이러한 objects들을 프로그래머가 모두 없애줘야하는데 이게 장점이자 단점이다. hardware를 직접 control이 가능하기 때문. memory를 할당하고 해제하는 것이 가능. 근데 자바나 파이썬은 이게 불가능하다.

list print

>>> a = [1,2,3,4]
>>> print(a)
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]
>>> for i in range(len(a)):
	print(a[i], end=' ')

	
1 2 3 4 
>>> for i in a:
	print(i, end=' ')

	
1 2 3 4 
>>> print(*a)
1 2 3 4
>>> print(*a, sep=', ')
1, 2, 3, 4
>>> a = ('a', 'nice', 'day')
>>> print(*a)
a nice day
>>> print(*a, sep=', ')
a, nice, day

음.. list를 출력하는 다양한 방법에 대해서 적어 보았다. 물론 그냥 a이렇게 치는 것은 원래는... python에서는 안 되는데 이것이 지금 ipython환경이라서 출력이 되는 거다.
for loop나 *연산자를 통해서 출력을 할 수 있는데 이 때에는 seperation을 지정할 수 있다.

list comprehension

>>> a = [i**3 for i in [1,2,3,4]]
>>> a
[1, 8, 27, 64]
>>> a = [i*i for i in [1,2,3,4]]
>>> a
[1, 4, 9, 16]
>>> a=[]
>>> for i in [1,2,3,4]:
	a.append(i**2)

	
>>> a
[1, 4, 9, 16]
>>> a = [-i for i in range(10) if i%2==0]
>>> print(a)
[0, -2, -4, -6, -8]
>>> fruits = ["apple", 'banana', "kiwi"]
>>> a = [s for s in fruits if 'a' in s]
>>> a
['apple', 'banana']
>>> print(a)
['apple', 'banana']

list comprehension은 python 코드를 줄이는 방법 중 하나이다. 다른 언어 같은 경우 3줄 이렇게 써야되는 code들을 단 한 줄로 적을 수 있는 강력한 tool이다. if 조건문도 함께 쓸 수 있는데 그 경우 조건에 해당하는 인자들만 list에 넣어준다.

profile
Written by coh

0개의 댓글