Hướng dẫn python iterate over module attributes - python lặp qua các thuộc tính mô-đun

Bạn có thể sử dụng

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
1 bằng cách nào đó như thế này:

for name, val in foo.__dict__.iteritems(): # iterate through every module's attributes
    if callable(val):                      # check if callable (normally functions)
        val()                              # call it

Nhưng coi chừng, điều này sẽ thực thi mọi hàm (có thể gọi) trong mô -đun. Nếu một số chức năng cụ thể nhận được bất kỳ đối số, nó sẽ thất bại.

Một cách thanh lịch hơn (chức năng) để có được các chức năng sẽ là:

[f for _, f in foo.__dict__.iteritems() if callable(f)]

Ví dụ, điều này sẽ liệt kê tất cả các chức năng trong phương thức

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
2:

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]


Mô -đun này thực hiện một số khối xây dựng vòng lặp lấy cảm hứng từ các cấu trúc từ APL, Haskell và SML. Mỗi người đã được thu hồi trong một hình thức phù hợp cho Python.iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.

Mô -đun chuẩn hóa một bộ lõi của các công cụ nhanh, hiệu quả bộ nhớ hữu ích cho chính chúng hoặc kết hợp. Cùng nhau, họ tạo thành một đại số iterator của người Viking, giúp việc xây dựng các công cụ chuyên dụng một cách ngắn gọn và hiệu quả trong Python thuần túy.

Chẳng hạn, SML cung cấp một công cụ lập bảng:

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
3 tạo ra chuỗi
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
4. Hiệu ứng tương tự có thể đạt được trong Python bằng cách kết hợp
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
5 và
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
6 để tạo thành
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
7.

Các công cụ này và các đối tác tích hợp của chúng cũng hoạt động tốt với các chức năng tốc độ cao trong mô-đun

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
8. Ví dụ, toán tử nhân có thể được ánh xạ trên hai vectơ để tạo thành một sản phẩm chấm hiệu quả:
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
9.

Vòng lặp vô hạn:

Người lặp lại

Tranh luận

Kết quả

Thí dụ

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
6

Bắt đầu, [Bước]

Bắt đầu, bắt đầu+bước, bắt đầu+2*Bước,

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
1

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
2

P

P0, P1, Plast Plast, P0, P1, Mạnh

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
3

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
4

elem [, n]

elem, elem, elem,… vô tận hoặc lên đến n lần

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
5

Trình lặp chấm dứt trên chuỗi đầu vào ngắn nhất:

Người lặp lại

Tranh luận

Kết quả

Thí dụ

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
6

Bắt đầu, [Bước]

Bắt đầu, bắt đầu+bước, bắt đầu+2*Bước,

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
7

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
8

P

P0, P1, Plast Plast, P0, P1, Mạnh

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
9

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
0

elem [, n]

P0, P1, Plast Plast, P0, P1, Mạnh

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
1

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
2

elem [, n]

elem, elem, elem,… vô tận hoặc lên đến n lần

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
3

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
4

Trình lặp chấm dứt trên chuỗi đầu vào ngắn nhất:

P [, func]

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
5

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
6

Trình lặp chấm dứt trên chuỗi đầu vào ngắn nhất:

P [, func]

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
7

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
8

P0, P0+P1, P0+P1+P2,

P, Q,…

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
9

P0, P1, Plast Plast, Q0, Q1, Mạnh

Có thể lặp lại

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
0

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
1

elem [, n]

elem, elem, elem,… vô tận hoặc lên đến n lần

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
2

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
3

Trình lặp chấm dứt trên chuỗi đầu vào ngắn nhất:

P [, func]

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
4

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
5

Trình lặp chấm dứt trên chuỗi đầu vào ngắn nhất:

P [, func]

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
6

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
7

P0, P0+P1, P0+P1+P2,

P, Q,…

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
8

P

P0, P1, Plast Plast, P0, P1, Mạnh

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
9

elem [, n]

Người lặp lại

Tranh luận

Kết quả

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
0

Thí dụ

Bắt đầu, [Bước]

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
1

Bắt đầu, bắt đầu+bước, bắt đầu+2*Bước,

P

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
2

P0, P1, Plast Plast, P0, P1, Mạnh

elem [, n]

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
3

P0, P1, Plast Plast, P0, P1, Mạnh

elem [, n]

elem, elem, elem,… vô tận hoặc lên đến n lần

Kết quả

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
4

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
5

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
6

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
7

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
8

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
9

def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)
0

def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)
1

Thí dụ

Bắt đầu, [Bước]

Bắt đầu, bắt đầu+bước, bắt đầu+2*Bước,accumulate(iterable[, func, *, initial=None])

P

P0, P1, Plast Plast, P0, P1, Mạnh

elem [, n]

elem, elem, elem,… vô tận hoặc lên đến n lần

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total

Trình lặp chấm dứt trên chuỗi đầu vào ngắn nhất:

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]

P [, func]

Mới trong phiên bản 3.2.

Đã thay đổi trong phiên bản 3.3: Đã thêm tham số func tùy chọn.Added the optional func parameter.

Đã thay đổi trong phiên bản 3.8: Đã thêm tham số ban đầu tùy chọn.Added the optional initial parameter.

itertools.chain (*iterables) ¶chain(*iterables)

Tạo một trình lặp lại trả về các phần tử từ lần lặp lại đầu tiên cho đến khi nó cạn kiệt, sau đó tiến hành đến phần tiếp theo, cho đến khi tất cả các vòng lặp bị cạn kiệt. Được sử dụng để xử lý các chuỗi liên tiếp như một chuỗi duy nhất. Tương đương với:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

classMethodChain.from_Iterable (itable) ¶ chain.from_iterable(iterable)

Hàm tạo thay thế cho

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
8. Được xiềng xích đầu vào từ một đối số có thể lặp lại duy nhất được đánh giá một cách lười biếng. Tương đương với:

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

itertools.combinations (Itable, R) ¶combinations(iterable, r)

Trả về r dài r tràng của các phần tử từ đầu vào có thể điều chỉnh được.

Các bộ dữ liệu kết hợp được phát ra theo thứ tự từ vựng theo thứ tự của đầu vào có thể điều chỉnh được. Vì vậy, nếu đầu vào có thể sắp xếp, các bộ dữ liệu đầu ra sẽ được sản xuất theo thứ tự sắp xếp.

Các yếu tố được coi là duy nhất dựa trên vị trí của chúng, không phải dựa trên giá trị của chúng. Vì vậy, nếu các phần tử đầu vào là duy nhất, sẽ không có giá trị lặp lại trong mỗi kết hợp.

Tương đương với:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

Mã cho

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
2 cũng có thể được biểu thị dưới dạng phần sau của
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
1 sau khi lọc các mục trong đó các phần tử không theo thứ tự được sắp xếp (theo vị trí của chúng trong nhóm đầu vào):

def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)

Số lượng các mặt hàng được trả về là

def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
1 khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
2 hoặc không khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
3.

itertools.comcombinations_with_replacement(iterable, r)

Trả về r dài các phần tử của các phần tử từ đầu vào có thể cho phép các phần tử riêng lẻ được lặp lại nhiều lần.

Các bộ dữ liệu kết hợp được phát ra theo thứ tự từ vựng theo thứ tự của đầu vào có thể điều chỉnh được. Vì vậy, nếu đầu vào có thể sắp xếp, các bộ dữ liệu đầu ra sẽ được sản xuất theo thứ tự sắp xếp.

Các yếu tố được coi là duy nhất dựa trên vị trí của chúng, không phải dựa trên giá trị của chúng. Vì vậy, nếu các phần tử đầu vào là duy nhất, sẽ không có giá trị lặp lại trong mỗi kết hợp.

Tương đương với:

def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

[f for _, f in foo.__dict__.iteritems() if callable(f)]
0

Mã cho

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
2 cũng có thể được biểu thị dưới dạng phần sau của
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
1 sau khi lọc các mục trong đó các phần tử không theo thứ tự được sắp xếp (theo vị trí của chúng trong nhóm đầu vào):

Số lượng các mặt hàng được trả về là

def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
1 khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
2 hoặc không khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
3.

itertools.comcompress(data, selectors)

Trả về r dài các phần tử của các phần tử từ đầu vào có thể cho phép các phần tử riêng lẻ được lặp lại nhiều lần.

Các yếu tố được coi là duy nhất dựa trên vị trí của chúng, không phải dựa trên giá trị của chúng. Vì vậy, nếu các phần tử đầu vào là duy nhất, các kết hợp được tạo cũng sẽ là duy nhất.

Số lượng các mặt hàng được trả về là

def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
1 khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
2 hoặc không khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
3.

itertools.comcount(start=0, step=1)

Trả về r dài các phần tử của các phần tử từ đầu vào có thể cho phép các phần tử riêng lẻ được lặp lại nhiều lần.

[f for _, f in foo.__dict__.iteritems() if callable(f)]
2

Các yếu tố được coi là duy nhất dựa trên vị trí của chúng, không phải dựa trên giá trị của chúng. Vì vậy, nếu các phần tử đầu vào là duy nhất, các kết hợp được tạo cũng sẽ là duy nhất.

Mã cho

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
3 cũng có thể được biểu thị dưới dạng theo sau
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
0 sau khi lọc các mục trong đó các phần tử không theo thứ tự được sắp xếp (theo vị trí của chúng trong nhóm đầu vào):Added step argument and allowed non-integer arguments.

Số lượng các mặt hàng được trả lại là
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
6 khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
7.
cycle(iterable)

Mới trong phiên bản 3.1.

[f for _, f in foo.__dict__.iteritems() if callable(f)]
3

itertools.compress (dữ liệu, bộ chọn) ¶

Tạo một trình lặp lại lọc các phần tử từ dữ liệu chỉ trả về các yếu tố có phần tử tương ứng trong các bộ chọn đánh giá thành
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
8. Dừng khi các phép lặp dữ liệu hoặc bộ chọn đã bị cạn kiệt. Tương đương với:
dropwhile(predicate, iterable)

[f for _, f in foo.__dict__.iteritems() if callable(f)]
1

[f for _, f in foo.__dict__.iteritems() if callable(f)]
4

itertools.count (start = 0, bước = 1) ¶filterfalse(predicate, iterable)

Tạo một trình lặp lại trả về các giá trị cách đều nhau bắt đầu bằng việc bắt đầu số. Thường được sử dụng như một đối số cho

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
5 để tạo các điểm dữ liệu liên tiếp. Ngoài ra, được sử dụng với
[f for _, f in foo.__dict__.iteritems() if callable(f)]
00 để thêm số thứ tự. Tương đương với:

[f for _, f in foo.__dict__.iteritems() if callable(f)]
5

Khi đếm với số điểm nổi, độ chính xác tốt hơn đôi khi có thể đạt được bằng cách thay thế mã nhân như:
[f for _, f in foo.__dict__.iteritems() if callable(f)]
01.
groupby(iterable, key=None)

Đã thay đổi trong phiên bản 3.1: Đã thêm đối số bước và cho phép đối số không số nguyên.

itertools.cycle (có thể lặp lại) ¶

Nhóm được trả lại tự nó là một trình lặp lại chia sẻ những điều không thể sử dụng được với

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
8. Bởi vì nguồn được chia sẻ, khi đối tượng
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
8 được nâng cao, nhóm trước không còn hiển thị. Vì vậy, nếu dữ liệu đó là cần thiết sau này, nó sẽ được lưu trữ dưới dạng danh sách:

[f for _, f in foo.__dict__.iteritems() if callable(f)]
6

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
8 gần tương đương với:

[f for _, f in foo.__dict__.iteritems() if callable(f)]
7

itertools.islice (itable, stop) ¶ itertools.islice (itable, start, stop [, bước])islice(iterable, stop)itertools.islice(iterable, start, stop[, step])

Tạo một trình lặp lại trả về các phần tử được chọn từ ITBERABLE. Nếu bắt đầu là không khác, thì các phần tử từ IT có thể bỏ qua cho đến khi đạt được bắt đầu. Sau đó, các yếu tố được trả về liên tiếp trừ khi bước được đặt cao hơn một phần dẫn đến các mục bị bỏ qua. Nếu điểm dừng là

[f for _, f in foo.__dict__.iteritems() if callable(f)]
03, thì lần lặp tiếp tục cho đến khi máy lặp bị cạn kiệt, nếu có; Nếu không, nó dừng ở vị trí quy định.

Nếu bắt đầu là

[f for _, f in foo.__dict__.iteritems() if callable(f)]
03, thì lần lặp lại bắt đầu từ 0. Nếu bước là
[f for _, f in foo.__dict__.iteritems() if callable(f)]
03, thì bước mặc định là một.

Không giống như cắt thông thường,

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
9 không hỗ trợ các giá trị âm cho bắt đầu, dừng hoặc bước. Có thể được sử dụng để trích xuất các trường liên quan từ dữ liệu trong đó cấu trúc bên trong đã được làm phẳng (ví dụ: một báo cáo đa dòng có thể liệt kê một trường tên trên mỗi dòng thứ ba).

Tương đương với:

[f for _, f in foo.__dict__.iteritems() if callable(f)]
8

itertools.pairwise (có thể lặp lại) ¶pairwise(iterable)

Trả về các cặp chồng chéo liên tiếp được lấy từ đầu vào có thể điều chỉnh được.

Số lượng 2 bộ trong đầu ra đầu ra sẽ ít hơn số lượng đầu vào. Nó sẽ trống nếu đầu vào có thể có ít hơn hai giá trị.

Tương đương với:

[f for _, f in foo.__dict__.iteritems() if callable(f)]
9

itertools.pairwise (có thể lặp lại) ¶

Trả về các cặp chồng chéo liên tiếp được lấy từ đầu vào có thể điều chỉnh được.permutations(iterable, r=None)

Số lượng 2 bộ trong đầu ra đầu ra sẽ ít hơn số lượng đầu vào. Nó sẽ trống nếu đầu vào có thể có ít hơn hai giá trị.

Mới trong phiên bản 3.10.

itertools.permutations (itable, r = none) ¶

Trả lại hoán vị chiều dài r liên tiếp của các phần tử trong ITBERSEBLE.

Tương đương với:

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
0

itertools.pairwise (có thể lặp lại) ¶

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
1

Trả về các cặp chồng chéo liên tiếp được lấy từ đầu vào có thể điều chỉnh được.

Số lượng 2 bộ trong đầu ra đầu ra sẽ ít hơn số lượng đầu vào. Nó sẽ trống nếu đầu vào có thể có ít hơn hai giá trị.product(*iterables, repeat=1)

Mới trong phiên bản 3.10.

itertools.permutations (itable, r = none) ¶

Trả lại hoán vị chiều dài r liên tiếp của các phần tử trong ITBERSEBLE.

Nếu R không được chỉ định hoặc là

[f for _, f in foo.__dict__.iteritems() if callable(f)]
03, thì r mặc định theo chiều dài của độ dài và tất cả các hoán vị có độ dài đầy đủ có thể được tạo ra.

Các bộ dữ liệu hoán vị được phát ra theo thứ tự từ vựng theo thứ tự của đầu vào có thể điều chỉnh được. Vì vậy, nếu đầu vào có thể sắp xếp, các bộ dữ liệu đầu ra sẽ được sản xuất theo thứ tự sắp xếp.

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
2

Các yếu tố được coi là duy nhất dựa trên vị trí của chúng, không phải dựa trên giá trị của chúng. Vì vậy, nếu các phần tử đầu vào là duy nhất, sẽ không có giá trị lặp lại trong một hoán vị.

Mã cho
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
1 cũng có thể được biểu thị dưới dạng phần sau của
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
0, được lọc để loại trừ các mục với các phần tử lặp lại (các phần tử từ cùng một vị trí trong nhóm đầu vào):
repeat(object[, times])

Số lượng các mặt hàng được trả lại là

[f for _, f in foo.__dict__.iteritems() if callable(f)]
17 khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
2 hoặc không khi
def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
3.

Tương đương với:

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
3

itertools.pairwise (có thể lặp lại) ¶

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
4

Trả về các cặp chồng chéo liên tiếp được lấy từ đầu vào có thể điều chỉnh được.starmap(function, iterable)

Số lượng 2 bộ trong đầu ra đầu ra sẽ ít hơn số lượng đầu vào. Nó sẽ trống nếu đầu vào có thể có ít hơn hai giá trị.

Mới trong phiên bản 3.10.

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
5

itertools.permutations (itable, r = none) ¶takewhile(predicate, iterable)

Trả lại hoán vị chiều dài r liên tiếp của các phần tử trong ITBERSEBLE.

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
6

Nếu R không được chỉ định hoặc là
[f for _, f in foo.__dict__.iteritems() if callable(f)]
03, thì r mặc định theo chiều dài của độ dài và tất cả các hoán vị có độ dài đầy đủ có thể được tạo ra.
tee(iterable, n=2)

Các bộ dữ liệu hoán vị được phát ra theo thứ tự từ vựng theo thứ tự của đầu vào có thể điều chỉnh được. Vì vậy, nếu đầu vào có thể sắp xếp, các bộ dữ liệu đầu ra sẽ được sản xuất theo thứ tự sắp xếp.

Các yếu tố được coi là duy nhất dựa trên vị trí của chúng, không phải dựa trên giá trị của chúng. Vì vậy, nếu các phần tử đầu vào là duy nhất, sẽ không có giá trị lặp lại trong một hoán vị.

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
7

Mã cho

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
1 cũng có thể được biểu thị dưới dạng phần sau của
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
0, được lọc để loại trừ các mục với các phần tử lặp lại (các phần tử từ cùng một vị trí trong nhóm đầu vào):

[f for _, f in foo.__dict__.iteritems() if callable(f)]
31 iterators không phải là sleadSafe. Một
[f for _, f in foo.__dict__.iteritems() if callable(f)]
32 có thể được nâng lên khi sử dụng đồng thời lặp lại được trả về bởi cùng một cuộc gọi
def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
7, ngay cả khi bản gốc có thể sử dụng được là an toàn.

ITERTOOL này có thể yêu cầu lưu trữ phụ trợ đáng kể (tùy thuộc vào số lượng dữ liệu tạm thời cần được lưu trữ). Nói chung, nếu một người lặp sử dụng hầu hết hoặc tất cả dữ liệu trước khi một trình lặp khác bắt đầu, việc sử dụng

[f for _, f in foo.__dict__.iteritems() if callable(f)]
34 sẽ nhanh hơn thay vì
def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
7.

itertools.zip_longest (*iterables, fillValue = none) ¶zip_longest(*iterables, fillvalue=None)

Tạo một trình lặp tổng hợp các phần tử từ mỗi lần lặp. Nếu các vòng lặp có độ dài không đồng đều, các giá trị bị thiếu sẽ được lấp đầy bằng fillvalue. Lặp lại tiếp tục cho đến khi có thể cạn kiệt lâu nhất. Tương đương với:

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
8

Nếu một trong các vòng lặp có khả năng là vô hạn, thì hàm

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
8 nên được gói bằng một cái gì đó giới hạn số lượng cuộc gọi (ví dụ
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
9 hoặc
def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
5). Nếu không được chỉ định, FillValue mặc định là
[f for _, f in foo.__dict__.iteritems() if callable(f)]
03.

Công thức nấu ăn itertools

Phần này hiển thị các công thức nấu ăn để tạo một bộ công cụ mở rộng bằng cách sử dụng các itertools hiện có làm khối xây dựng.

Mục đích chính của các công thức nấu ăn là giáo dục. Các công thức nấu ăn cho thấy nhiều cách suy nghĩ khác nhau về các công cụ riêng lẻ - ví dụ,

[f for _, f in foo.__dict__.iteritems() if callable(f)]
40 có liên quan đến khái niệm làm phẳng. Các công thức nấu ăn cũng đưa ra ý tưởng về các cách mà các công cụ có thể được kết hợp - ví dụ: cách nén () và phạm vi () có thể hoạt động cùng nhau. Các công thức nấu ăn cũng hiển thị các mẫu để sử dụng itertools với các mô-đun
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
8 và
[f for _, f in foo.__dict__.iteritems() if callable(f)]
42 cũng như với các itertools tích hợp như
def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
5,
[f for _, f in foo.__dict__.iteritems() if callable(f)]
44,
[f for _, f in foo.__dict__.iteritems() if callable(f)]
45 và
[f for _, f in foo.__dict__.iteritems() if callable(f)]
46.

Mục đích thứ yếu của các công thức nấu ăn là phục vụ như một vườn ươm. ITERTOOLS

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
6,
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
2 và
def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
1 bắt đầu như là công thức nấu ăn. Hiện tại, công thức
[f for _, f in foo.__dict__.iteritems() if callable(f)]
50 đang được thử nghiệm để xem liệu nó có chứng minh được giá trị của nó hay không.

Về cơ bản, tất cả các công thức nấu ăn này và nhiều, nhiều công thức khác có thể được cài đặt từ dự án nhiều hơn được tìm thấy trên Chỉ số gói Python:

import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]
9

Nhiều công thức nấu ăn cung cấp hiệu suất cao giống như bộ công cụ cơ bản. Hiệu suất bộ nhớ vượt trội được giữ bằng cách xử lý các yếu tố một lần thay vì đưa toàn bộ bộ nhớ vào bộ nhớ cùng một lúc. Khối lượng mã được giữ nhỏ bằng cách liên kết các công cụ với nhau theo kiểu chức năng giúp loại bỏ các biến tạm thời. Tốc độ cao được giữ lại bằng cách ưu tiên các khối xây dựng vectơ hóa của Vectơ hơn việc sử dụng các vòng lặp và máy phát điện phải chịu chi phí thông dịch.generators which incur interpreter overhead.

def accumulate(iterable, func=operator.add, *, initial=None):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = initial
    if initial is None:
        try:
            total = next(it)
        except StopIteration:
            return
    yield total
    for element in it:
        total = func(total, element)
        yield total
0