gpt4 book ai didi

python - 如何使用 python itertools 模块

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:09 25 4
gpt4 key购买 nike

我有以下代码:

import itertools


x = ['Lebron' 'James']
y = ['is', 'the', 'goat']
z = ['is', 'not', 'the', 'goat']
itertools.chain(x, y)

我得到以下输出:itertools.chain at 0x104baab50

这个输出是什么意思?我怎样才能看到该方法的结果?


然后下面的代码也是一样的:

itertools.chain.from_iterable([x,y])

我得到以下输出:itertools.chain at 0x104af7550

这是什么意思?我怎样才能看到该方法的实际结果?我不太确定这两种方法之间有什么区别。

最佳答案

itertools.chain 返回一个迭代器,允许您通过 __next__ 等在 for 循环中迭代值。like a regular Python iterator .

例如:

In [3]: import itertools
...: x = ['Lebron', 'James']
...: y = ['is', 'the', 'goat']
...: z = ['is', 'not', 'the', 'goat']

In [4]: for thing in x:
...: print('Thing is', thing)
...:
Thing is Lebron
Thing is James

In [5]: for thing in itertools.chain(x, y):
...: print('Thing is', thing)
...:
Thing is Lebron
Thing is James
Thing is is
Thing is the
Thing is goat

from_iterable获取可迭代对象(例如其他列表)的可迭代对象(例如列表)并依次迭代每个:

In [8]: for thing in itertools.chain.from_iterable([x, y]):
...: print('Thing is', thing)
...:
Thing is Lebron
Thing is James
Thing is is
Thing is the
Thing is goat

关于python - 如何使用 python itertools 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com