파이썬[Python]: itertools - count 함수

파이썬(Phthon): itertools 모듈 - count 함수(function)


/// 설명

인자 start에서 시작하여 step 단위만큼 차이가 생기는 값들을 반환하는 이터레이터를 생성합니다. map() 이나 zip()에 자주 사용됩니다.

※ 형식
itertools.count(start=0, step=1)

reference
https://docs.python.org/3/library/itertools.html#module-itertools

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import itertools
 
test_count = itertools.count()
print(next(test_count))  # 0
print(next(test_count))  # 1
print(next(test_count))  # 2
# print(next(test_count))
# ...
# ... endless
 
test_str = 'This is a string.\n'
str_count = 0
 
for i in itertools.count():
    if test_str[i] == '\n':
        break
    else:
        str_count += 1
 
print('length: ', str_count)  # length:  17
 
test_f = 0.0
test_step = 0.5
for i in itertools.count(0.0, test_step):
    if test_f < 5:
        print(i, end='  ')  # 0.0  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5
 
        test_f += test_step
    else:
        break
 
print()
 
test_f = 0.0
test_step = 0.5  # better accuracy
test_b_counter = (test_step * i for i in itertools.count())
for i in test_b_counter:
    if test_f < 5:
        print(i, end='  ')  # 0.0  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5
 
        test_f += test_step
    else:
        break
 
cs

* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)


– 당신을 응원합니다. –

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

파이썬[Python]: 내장함수 - bit_length 메서드

C 언어: sin 함수, cos 함수, tan 함수