Seite 1 von 1

Itertools frage...

Verfasst: Freitag 25. Oktober 2013, 13:23
von Eliazz

Code: Alles auswählen

import itertools
a = itertools.combinations('ABCD',  2)
print(a)
# Es sollte eigentlich 'AB AC AD BC BD CD' herauskommen...
import itertools


Irgendwie kriege ich so ne komische ausgabe... Laut Tutorial müsste was anderes rauskommen, wo ist der Fehler?
(Siehe Auch link: http://docs.python.org/2/library/itertools.html --> Combinatoric generators:
MFG

Re: Itertools frage...

Verfasst: Freitag 25. Oktober 2013, 13:37
von lackschuh
Vielleicht durchiterieren?

Code: Alles auswählen

for i in a:
    print i

Re: Itertools frage...

Verfasst: Freitag 25. Oktober 2013, 13:38
von BlackJack
@Eliazz: Die Funktion hat als Rückgabewert einen Iterator (darum steckt die Funktion auch im Modul `itertools`) und *der* generiert die Kombinationen wenn man darüber iteriert, und zwar eine nach der anderen und nicht alle auf einmal:

Code: Alles auswählen

In [9]: itertools.combinations('ABCD', 2)
Out[9]: <itertools.combinations at 0x929189c>

In [10]: cs = itertools.combinations('ABCD', 2)

In [11]: next(cs)
Out[11]: ('A', 'B')

In [12]: next(cs)
Out[12]: ('A', 'C')

In [13]: next(cs)
Out[13]: ('A', 'D')

In [14]: next(cs)
Out[14]: ('B', 'C')

In [15]: next(cs)
Out[15]: ('B', 'D')

In [16]: next(cs)
Out[16]: ('C', 'D')

In [17]: next(cs)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
/home/bj/<ipython-input-17-2473a9b0b1c8> in <module>()
----> 1 next(cs)

StopIteration: 

In [18]: cs = itertools.combinations('ABCD', 2)

In [19]: for c in cs:
   ....:     print c
   ....: 
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'C')
('B', 'D')
('C', 'D')

In [20]: cs = itertools.combinations('ABCD', 2)

In [21]: list(cs)
Out[21]: [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

Re: Itertools frage...

Verfasst: Freitag 25. Oktober 2013, 20:13
von snafu

Code: Alles auswählen

Python 3.3.0 (default, Sep 25 2013, 19:28:08) 
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import combinations
>>> pairs = map(''.join, combinations('ABCD', 2))
>>> print(*pairs)
AB AC AD BC BD CD