Accessing elements of itertools product in a for loop

前端 未结 2 1855
我寻月下人不归
我寻月下人不归 2021-01-29 11:45

I have a list of list being the result of appending some other results from itertools product. What I want is to be able to access each element of the lists in the list of lists

2条回答
  •  忘掉有多难
    2021-01-29 11:59

    itertools.product itself returns an object you can iterate over. For example:

    >>> from itertools import product
    >>> animal = ['dog','cat']
    >>> number = [5,45,8,9]
    >>> color = ['yellow','blue','black']
    >>> myProduct = product(animal, number, color)
    >>> for p in myProduct:
    ...     print p
    ...     
    ('dog', 5, 'yellow')
    ('dog', 5, 'blue')
    ('dog', 5, 'black')
    [...]
    ('cat', 9, 'blue')
    ('cat', 9, 'black')
    

    After this, myProduct is exhausted (out of elements to yield) and so if you loop again you won't get anything:

    >>> for p in myProduct:
    ...     print p
    ...     
    >>> 
    

    If you want to materialize myProduct into a list, you can do that:

    >>> myProduct = list(product(animal, number, color))
    >>> len(myProduct)
    24
    >>> myProduct[7]
    ('dog', 8, 'blue')
    

    By appending the product object itself to a list, you're not getting the list iterating it would produce, only the object.

    >>> myProduct = product(animal, number, color)
    >>> myProduct
    
    

    If you want, you can store this object somewhere, and get elements from it the same way:

    >>> some_list = [myProduct, myProduct]
    >>> next(some_list[0])
    ('dog', 5, 'yellow')
    >>> next(some_list[1])
    ('dog', 5, 'blue')
    >>> next(some_list[1])
    ('dog', 5, 'black')
    >>> next(some_list[0])
    ('dog', 45, 'yellow')
    

    but here I don't think that's what you're looking for.

提交回复
热议问题