공부하다가 귀찮지 않을때 정리 / 차차 업데이트
Iterators
1. Iterable vs. Iterators
Iterables 는 에를들어 list, strings, dictionary, file connection 등으로 iter() 메소드와 연관이 있는 것들이나. Iter() 메소드는 Iterable 들이 Iterator 를 생성시키는데 적용한다.
Iterator 는 next() 로 다음 value 를 생성한다.
예제)
> example='dog'
> it = iter(example)
> next(it)
>> 'd'
> next(it)
>> 'o'
> next(it)
>> 'g'
> next(it)
>> 출력안됨
2. * operator(star operator)
위의 예제를
> next(*it) 이런식으로 출력하면 한꺼번에 d o g 로 출력된다.
3. Enumerate()
enumerate() 로 어떤 리스트를 타입변형 시킬수 있음.
예를들어서,
> animal = ['dog', 'cat', 'mouse']
>
> for index, value in enumerate(animal) :
> print(index, value)
>
>> 0 dog
>> 1 cat
>> 2 mouse
>
>
> for index, value in enumerate(animal, start=10) 으로 하면 index 가 10부터 시작됨
4. zip()
zip() 은 튜플의 iterator 형태. 두 가지 리스트를 한꺼번에 zip 할 수 있음
> z=zip(animal, plant)
>
> z_list = list(z)
> print(z_list)
zip() 오브젝트의 unpack 은 for loop 로
> for z1, z2 in zip(animal, plant) 이렇게 해서 프린트하면 됨
zip 에서도 star operator * 쓸수 있음
5. 헷갈렸던 예제 부분
# Create a list of tuples: animal_list
animal_list = list(enumerate(animal))
6. 빅데이터에 사용되는 iterator
pandas 사용해서 read_csv() 하고, chunksize 로 specify 할 수 있다.
import pandas 해서, empty list 만들고,
for chunk in pd.read_csv(경로, chunksize=1000)
result.append(sum(chunk['x'])
이런식으로...
아니면 리스트 대신 파이널값을 0으로 셋 해놓고,
for 문 안에 final += sum(chunk['x])
이런식으로 짜도 된다.
'Python' 카테고리의 다른 글
파이썬 Hackers statistics, 랜덤 시뮬레이션 (0) | 2018.06.07 |
---|---|
파이썬 로직, 데이터 컨트롤, 데이터 필터링 정리 (0) | 2018.06.07 |
Python Dictionary&Pandas 파이썬 딕셔너리, 판다스 총 정리! (0) | 2018.06.07 |
Python Matplotlib 패키지 총 정리! 유용한 팁 모음 (0) | 2018.06.07 |
Python 파이썬 메소드의 개념. 쉽게 알기! (0) | 2018.06.05 |