开发者

Python returning `<itertools.combinations object at 0x10049b470>` - How can I access this?

I have this simple piece of code that returns what's in the title. Why doesn't the array simply print? This is not just an itertools issue I've also noticed it for other code wher开发者_如何转开发e it'll just return the object location.

Here is the code. I'm running 2.7.1, an enthought distribution (pylab) - using it for class.

import itertools

number = [53, 64, 68, 71, 77, 82, 85]

print itertools.combinations(number, 4)


It doesn't print a simple list because the returned object is not a list. Apply the list function on it if you really need a list.

print list(itertools.combinations(number, 4))

itertools.combinations returns an iterator. An iterator is something that you can apply for on. Usually, elements of an iterator is computed as soon as you fetch it, so there is no penalty of copying all the content to memory, unlike a list.


Try this:

for x in itertools.combinations(number, 4):
   print x

Or shorter:

results = [x for x in itertools.combinations(number, 4) ]

Basically, all of the itertools module functions return this type of object. The idea is that, rather than computing a list of answers up front, they return an iterable object that 'knows' how to compute the answers, but doesn't do so unless `asked.' This way, there is no significant up front cost for computing elements. See also this very good introduction to generators.


Beside the proposed solutions, other ways, with a little change to your code, you can do:

1)

import itertools

number = [53, 64, 68, 71, 77, 82, 85]

res = itertools.combinations(number, 4)

print(*res)

Put the result of the combination into a variable (res), after, with print, use a single asterisks * to unpacks the sequence/collection into positional arguments. More detail is in here.

2)

import itertools

number = [53, 64, 68, 71, 77, 82, 85]

*res, = itertools.combinations(number, 4)

print(res)

This in python 3, it called "Extended Iterable Unpacking"

A good tutorials about using Asterisks (*, **) in here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜