python itertools模块chain函数功能详解 itertools.chain(*iterable)

2023-11-19

Itertools模块, itertools提供了高效快捷的用于操作迭代对象的函数。通过使用这个模块,可以简化代码。

Itertools.chain语法

Itertools.chain(*iterables)

*代表接受可变的参数

iterables,迭代对象(序列),可以使用for in 遍历的对象,包括list, string, dict。

1.Itertools.chain功能1:去除iterable里的内嵌iterable,如去除列表中的内嵌列表;

例子1.1 去除列表a中的内嵌元组;

import itertools as it
a=[(1, 'a'), (2, 'b'), (3, 'c')]
a_update=it.chain(*a)
print(type(a_update)) #itertools返回的对象是个类
print(list(a_update)) #转化成列表输出

程序运行结果为:

<class 'itertools.chain'>
[1, 'a', 2, 'b', 3, 'c']

例子1.2 去除列表b中的内嵌列表;

import itertools as it
b=[[1,2],[5,6],[8,9]]
b_update=it.chain(*b)
print(type(b_update)) #itertools返回的对象是个类
print(list(b_update)) #转化成列表输出

 程序运行结果为:

<class 'itertools.chain'>
[1, 2, 5, 6, 8, 9]

例子1.3 去除列表b中的内嵌字典; 

import itertools as it
c=[{1,2},{3,4},{5,6}]
c_update=it.chain(*c)
print(type(c_update)) #itertools返回的对象是个类
print(list(c_update)) #转化成列表输出

           程序运行结果为:

<class 'itertools.chain'>
[1, 2, 3, 4, 5, 6]

       

     2.Itertools.chain功能2:两个序列的组合

     例子2.1(类似python自带的+)

import itertools as it
a=[1,2,3]
b=[4,5,6]
print(a+b)
print(list(it.chain(*(a,b))))

           程序运行结果为:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

      例子2.2结合zip函数进行配对问题;假如有列表a代表编号为1-5的5名女生,有列表b代表编号为a-e的5名男生,现在让5名男生依次插入5名女生中间,两队合成一队,如何用代码表示?

import itertools as it
a=[1,2,3,4,5] #女生
b=['a','b','c','d','e'] #男生
ab=zip(a,b)
final=it.chain(*ab)
print(list(final))

            程序运行结果为:

[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e']

            例子2.3 合并字符串,并转换成列表(不同于python自带的+)

import itertools as it

m="abc"
n="def"
print(m+n)
print(list(it.chain(*(m,n))))

             程序运行结果为:

abcdef
['a', 'b', 'c', 'd', 'e', 'f']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python itertools模块chain函数功能详解 itertools.chain(*iterable) 的相关文章

随机推荐