A look at itertools chain method

The python itertools module is a collection of tools for handling iterators. I want to make an honest effort to break the habit of repetitive standard patterns of basic python functionality. For example…

We have a list of tuples.

a = [(1, 2, 3), (4, 5, 6)]
a = [(1, 2, 3), (4, 5, 6)]
a = [(1, 2, 3), (4, 5, 6)]

Enter fullscreen mode Exit fullscreen mode

In order to iterate over the list and the tuples, we have a nested for loop.

for x in a:
for y in x:
print(y)
# output
1
2
3
4
5
6
for x in a:
  for y in x:
    print(y)

 # output 

1
2
3
4
5
6
for x in a: for y in x: print(y) # output 1 2 3 4 5 6

Enter fullscreen mode Exit fullscreen mode

I have decided to challenge myself to start using all that itertools has to offer in my every day solutions. Today lets take a look at the chain method!

This first approach will only return the two tuples as as index 0 and 1. Instead of nesting another loop, lets apply the chain method.

from itertools import chain
a = [(1, 2, 3), (4, 5, 6)]
for _ in chain(a, b):
print(_)
# output
(1, 2, 3)
(4, 5, 6)
from itertools import chain

a = [(1, 2, 3), (4, 5, 6)]

for _ in chain(a, b):
  print(_)

 # output 
 (1, 2, 3)
 (4, 5, 6)
from itertools import chain a = [(1, 2, 3), (4, 5, 6)] for _ in chain(a, b): print(_) # output (1, 2, 3) (4, 5, 6)

Enter fullscreen mode Exit fullscreen mode

now we have access to iterate over the tuples without nesting another iteration with a for loop.

for _ in chain.from_iterable(a):
print(_)
# output
1
2
3
4
5
6
for _ in chain.from_iterable(a):
  print(_)

# output

1
2
3
4
5
6
for _ in chain.from_iterable(a): print(_) # output 1 2 3 4 5 6

Enter fullscreen mode Exit fullscreen mode

I think the chain method gives the flexibility to use this as a default choice for list iteration.

原文链接:A look at itertools chain method

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
Judge each day not by the harvest you reap but by the seeds you plant.
不要问自己收获了多少果实,而是要问自己今天播种了多少种子
评论 抢沙发

请登录后发表评论

    暂无评论内容