程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Use of itertools in Python

編輯:Python

Today I learned about python Built in modules itertools Use , Familiar with , See if you can write less in the future for, Hey .

Original link :Hzy Blog


1. Infinite iterators


1.1 count(start,[step])

count() Take two parameters

  • start: The number at the beginning of the cycle
  • step: The interval in the loop
from itertools import count
"""
Infinite iterators count()
"""
c = count(0, 2)
v = next(c)
while v < 10:
v = next(c)
print(v, end=',')

1.2 cycle()

cycle It's one while True, The numbers in the infinite loop .

"""
Infinite iterators cycle()
"""
from itertools import cycle
c = cycle('ABCD')
for i in range(10):
print(next(c), end=',')

1.3 repeat(elem,[n])

Repeat iteration elem,n Time

"""
Infinite iterators repeat()
"""
from itertools import repeat
r = repeat(1, 3)
for i in range(3):
print(next(r), end=',')

2. iterator


2.1 accumulate(p,[func])

Use func The function of iterates over the object p Accumulate .

"""
iterator accumulate()
"""
from itertools import accumulate
test_list = [i for i in range(1, 11)]
for i in accumulate(test_list): # The default is operator.add
print(i, end=',')
print()
for i in accumulate(test_list, lambda x, y: x * y): # operator.mul
print(i, end=',')

2.2 chain()

chain() Multiple iteration objects can be placed in the , Then iterate one by one .

"""
iterator chain()
"""
from itertools import chain
ch = chain([1, 2, 3], {4: 4, 5: 5}, {6, 7, 8}, (9,), [10, [11, 12]])
for i in ch:
print(i)

2.3 chain.from_iterable()

Follow chain The difference is this :

  • chain: Multiple iteration objects can be accepted
  • chain.from_iterable(): It can accept an iterator that can generate iterative objects
"""
iterator chain.from_iterable()
"""
def gen_iterables():
for i in range(10):
yield range(i)
for i in chain.from_iterable(gen_iterables()):
print(i)

3.4 compress(data,selectors)

That's it. Just look at this s yes selectors The elements in .
(d[0] if s[0]), (d[1] if s[1]), ...

"""
iterator compress
"""
from itertools import compress
print(list(compress(['A', 'B', 'C', 'D'], [0, 1, 1, 1])))

3.5 dropwhile(pred,seq)

The condition for the beginning of the cycle is , Until I met for the first time dissatisfaction pred Conditions , Just started traversing .

"""
iterator dropwhile()
"""
from itertools import dropwhile
l = [1, 7, 6, 3, 8, 2, 10]
print(list(dropwhile(lambda x: x < 3, l)))

3.6 groupby

This feeling is very interesting , It's kind of like sql Medium group_by. It can be used on strings , List, etc .

  • Return key and , The content of the group
from itertools import groupby
# Group strings
for k, g in groupby('11111234567'):
print(k, list(g))
d = {1: 1, 2: 2, 3: 2}
# According to the dictionary value To group
for k, g in groupby(d, lambda x: d.get(x)):
print(k, list(g))

3.7 islice

This is to cut the iterative object , Negative numbers are not supported , It's kind of like range(1,10,2) such

from itertools import islice
print(list(islice('ABCDEFG', 2,3, None)))

3.8 zip_longest

This and zip It's like , The difference is :

  • zip The end depends on the shortest iteration object
  • zip_longest The end depends on the longest iteration object
from itertools import zip_longest
for x,y in zip_longest([1,2,3],[1,2]):
print(x,y)
for x,y in zip([1,2,3],[1,2]):
print(x,y)

Permutation and combination iterators


3.1 product

amount to Nested for

“”"
Permutation and combination iterators product Nested for
“”"
from itertools import product
for i,j in product([1,2,3],[4,5]):
print(i,j

3.2 permutations

Full Permutation , Like output 123 All about .(1,2,3),(1,3,2)…

from itertools import permutations
print(list(permutations('123')))

3.3 combinations(p,r)

from p Find all the length in the r The arrangement of … In order

from itertools import combinations
print(list(combinations([1,2,3],2)))

3.4 combinations_with_replacement()

from p Find all the length in the r The arrangement of , In order , But including itself means repetition .

  • combinations_with_replacement(‘ABCD’, 2)
  • AA AB AC AD BB BC BD CC CD DD

Understanding is understanding , I don't know if I can remember when I use it …


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved