본문 바로가기

PYTHON

[Python 파이썬] __getitem__() 를 이용한 튜플의 리스트, 리스트의 리스트 다루기 (Handling List of Tuples, List of Lists) // 리스트 안에 튜플

 

리스트 안에 튜플 [(1,'hi'), (2,'hello'), (3,'hola')] 이렇게 된 리스트를 본적이 있으신가요?

그리고 그 안에 1, 2, 3 과 'hi', 'hello', 'hola'를 각자 불러오고 싶을때는요?

 

어떻게 하면 그 안의 값들을 다루고 사용할 수 있는지 알아봅시다.

 

 

 

가끔 우리는 리스트를 사용하면서 내부 element로 원시값이 아닌 객체형태, 즉 tuple 등의 자료구조를 사용할 때가 있다.

 

그리고 그때 ! 리스트 안에 있는 각 튜플의 동일 index에 존재하는 값 만을 추출하고 싶은 경우가 있다.

 

 

>>> a = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia"),(1,"shiwoo")]
>>> 
>>> a
[(1, 'juca'), (22, 'james'), (53, 'xuxa'), (44, 'delicia'), (1, 'shiwoo')]
>>> 
>>> [x[0] for x in a]   # 각 튜플의 첫번째 element만 list 형태로 추출
[1, 22, 53, 44, 1]
>>> 
>>> [x[1] for x in a]   # 각 튜플의 두번째 element만 list 형태로 추출
['juca', 'james', 'xuxa', 'delicia', 'shiwoo']

빨간 명령문에 주목하자.

마치 람다 표현식 비슷해 보이는 문법이다. 간단히 설명하면,

 

Python 은 List, Tuple안의 특정 element를 꺼낼 때,

객체의 built_in 함수인 '__getitem__' 을 호출하여 해당 index에 있는 값 추출을 시도한다.

python documentation 에 쓰여있는 설명을 잠시 보도록 하자.

 

object.__getitem__(self, key)

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexErrorshould be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

 

Note   

for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.

 

어떤 객체이던 간에 해당 객체가 x일 경우 x[key] 형태로 쓰인 문법에 직속으로 호출되는 함수임을 알 수 있다.

 

즉, 자신이 직접 만든 객체이더라도 __getitem__이라는 함수를 Override하게 된다면

그 객체를 선언하여 사용할때, x[key] 형태로 해당 객체의 특정 값을 호출 할 수 있게되는 것이다.

 

그럼 이번에는 리스트에 dictionary를 넣은 예제를 살펴보자.

 

total_list = []
a = dict()
b = dict()
c = dict()
d = dict()

# name이라는 key의 값으로 튜플과 리스트를 섞어서 지정해보자.
a["name"] = ["a_name", 11]
b["name"] = ("b_name", 22)
c["name"] = ["c_name", 33]
d["name"] = ("d_name", 44)

total_list = [a,b,c,d]

print total_list
# [{'name': ['a_name', 11]}, {'name': ('b_name', 22)}, {'name': ['c_name', 33]}, {'name': ('d_name', 44)}]

result_1 = [x["name"] for x in total_list]

print result_1
# [['a_name', 11], ('b_name', 22), ['c_name', 33], ('d_name', 44)]

result_2 = [x["name"][1] for x in total_list]

print result_2
# [11, 22, 33, 44]

이번에는 리스트 안에 동일한 key값을 가진 dictionary 객체를 넣어보았다.

그리고 각각의 key value는 또다시 튜플과 리스트로 지정하여 2차원 접근역시 가능하다는 것을 알수있다.

 

어떤가, 이제 확실히 이해가 가는가?

그리하여, 

 

결론 :

 

이렇게, 파이썬의 유연한 문법을 활용하여 어느 List안에 원시 자료형 값이 아닌

List, Tuple 혹은 자신이 직접만드는 객체(Class)가 들어있다 할지라도 __getitem__ 함수를 이용하여

손쉽게 그 값을 추출할 수 있다 !!!

 

 

 

출처:[Python 파이썬] __getitem__() 를 이용한 튜플의 리스트, 리스트의 리스트 다루기 (Handling List of Tuples, List of Lists)