如何在 Python 3.3.2 中导入 itertools

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16844494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:47:51  来源:igfitidea点击:

How to import itertools in Python 3.3.2

pythonnumpymodule

提问by Moderat

I'm running python (through IDLE, though I'm not sure what that is) on a Mac, version 3.3.2, and for some reason when I type from itertools import *it doesn't allow me to then use commands like chainand combinations. Additionally I can't seem to import numpyso I think I might have messed up the installation. Regards

我在 Mac 版本 3.3.2 上运行 python(通过 IDLE,虽然我不确定那是什么),并且由于某种原因,当我输入from itertools import *它时,它不允许我使用像chain和这样的命令combinations。此外,我似乎无法导入,numpy所以我想我可能把安装搞砸了。问候

Edit

编辑

As a minimal working example:

作为一个最小的工作示例:

>>> from itertools import chain
>>> chain('abc','def')
<itertools.chain object at 0x34c2130>

However, the output is supposed to be a b c d e f. So I'm not sure if I need to printthe result?

但是,输出应该是a b c d e f. 所以我不确定我是否需要print结果?

采纳答案by Gareth Latty

Firstly, you don't actually have a problem here. itertools.chain()does not return a list, it returns an iterable object. This is preferable as it is lazy (the values are not computed until they are needed) which is more memory-efficient.

首先,你在这里实际上没有问题。itertools.chain()不返回列表,它返回一个可迭代对象。这是更可取的,因为它是惰性的(直到需要时才计算值),这更节省内存。

It's worth noting if this had been an issue with importing modules, you would have had an exception, and it would have happened at the from itertools import chainline.

值得注意的是,如果这是导入模块的问题,您会遇到异常,并且会在from itertools import chain生产线上发生。

You can happily loop over it like you would any other iterable:

您可以像使用任何其他可迭代对象一样愉快地遍历它:

>>> from itertools import chain
>>> for item in chain('abc', 'def'):
...     print(item)
... 
a
b
c
d
e
f

This is the best way to use it, as it will be the most efficient. If you needa list (which you most likely do not), you can simply wrap the call with the list()built-in:

这是使用它的最佳方式,因为它将是最有效的。如果你需要一个列表(你很可能不需要),你可以简单地用list()内置函数包装调用:

>>> list(chain('abc', 'def'))
['a', 'b', 'c', 'd', 'e', 'f']