Python returning `` - How can I access this?

后端 未结 2 921
抹茶落季
抹茶落季 2020-12-24 07:17

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 notice

相关标签:
2条回答
  • 2020-12-24 07:47

    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.

    0 讨论(0)
  • 2020-12-24 07:47

    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.

    0 讨论(0)
提交回复
热议问题