Python官方文档关于itertools.chain()
的描述
1. chain()
函数的作用
chain()
函数的作用是将多个迭代器组合成一个序列,并返回一个迭代器对象。这个迭代器对象能够像序列一样迭代每一个元素。使用chain()
可以省去将多个迭代器合并成一个序列的麻烦。下面是使用chain()
函数的语法:
itertools.chain(*iterables)
其中,iterables
参数是可迭代对象,可以是多个序列、迭代器或可迭代对象。
2. chain()
函数的示例
import itertools
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
# 使用chain()组合lst1和lst2
lst3 = list(itertools.chain(lst1, lst2))
print(lst3) # [1, 2, 3, 4, 5, 6]
在这个例子中,我们使用chain()
函数将lst1
和lst2
两个列表组合成了一个新的列表lst3
,其中包含了lst1
和lst2
中的所有元素。
import itertools
s1 = 'hello'
s2 = 'world'
# 使用chain()组合s1和s2
s3 = ''.join(itertools.chain(s1, s2))
print(s3) # helloworld
在这个例子中,我们使用chain()
函数将s1
和s2
两个字符串组合成了一个新的字符串s3
,其中包含了s1
和s2
中的所有字符。由于字符串不能被修改,所以我们使用了join()
方法将结果转换为字符串。