如何安装itertools包?

8

我想尝试使用itertools模块中的permutations函数。但每次尝试实现时都会出现以下错误:

代码:

from itertools import permutations

txt=permutations('SKIN')
print(txt)

输出:

<itertools.permutations object at 0x7fee48665950>

我尝试在命令提示符上使用命令pip install itertools,但是一直遇到以下错误:

ERROR: Could not find a version that satisfies the requirement itertools (from versions: none)
ERROR: No matching distribution found for itertools

如何安装这个软件包?


2
这个输出并不是错误。它正确地返回了排列对象。如果你想使用迭代器,请尝试:for x in txt: print(x) - Kota Mori
5个回答

10

itertools是内置模块,无需安装:

Help on module itertools:

NAME
    itertools - Functional tools for creating and using iterators.

FILE
    /usr/lib64/python2.7/lib-dynload/itertoolsmodu

permutations(<iterable>)返回一个生成器,该生成器按顺序产生长度为r的可迭代对象中元素的排列组合:

>>> type(txt)
<type 'itertools.permutations'>

>>> dir(txt)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next']

期望排列列表:

list_perms = [ "".join(i) for i in permutations("SKIN")]

# ['SKIN', 'SKNI', 'SIKN', 'SINK', 'SNKI', 'SNIK', 'KSIN', 'KSNI', 'KISN', 'KINS', 'KNSI', 'KNIS', 'ISKN', 'ISNK', 'IKSN', 'IKNS', 'INSK', 'INKS', 'NSKI', 'NSIK', 'NKSI', 'NKIS', 'NISK', 'NIKS']

3

permutations() 返回一个对象,将其转换为列表即可完成工作。

from itertools import permutations

txt=list(permutations('SKIN'))
t = [''.join(i) for i in txt]
print(t)

1
我希望输出为['KINS','SINK',....],而不是[('K','I','N','S'),('S','I','N','K'),...] - user12735269

2
  • itertools 是 Python 中的内置模块,无需单独安装。
  • <itertools.permutations object at 0x7fee48665950> 不是错误。它是一个 迭代器。为了获取其中的内容,需要将其转换为列表。

可能的解决方案如下:

from itertools import permutations

txt = ["".join(_) for _ in permutations('SKIN')]

print(txt)

打印

['SKIN', 'SKNI', 'SIKN', 'SINK', 'SNKI', 'SNIK', 'KSIN', 'KSNI', 'KISN', 'KINS', 'KNSI', 'KNIS', 'ISKN', 'ISNK', 'IKSN', 'IKNS', 'INSK', 'INKS', 'NSKI', 'NSIK', 'NKSI', 'NKIS', 'NISK', 'NIKS']

0

你可以使用新版本,更多的工具。

pip install more-itertools

0

它的工作方式如预期。 permutations 是一个可以迭代的生成器。

from itertools import permutations

txt=permutations('SKIN')
print(txt)

for single_permutation in txt:
    print(single_permutation)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接