Accessing elements of itertools product in a for loop

前端 未结 2 1739
我寻月下人不归
我寻月下人不归 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 12:00

    Reading your post many times, I think you are interested in this syntax:

    for animal, number, color in ...:
    

    It allows you to access the elements from the inner lists.

    import itertools
    animals = ['dog', 'cat']
    numbers = [5, 45, 8, 9]
    colors = ['yellow', 'blue', 'black']
    for animal, number, color in itertools.product(animals, numbers, colors):
        print "Animal is {0}, number is {1}, and color is {2}".format(animal, number, color)
    

    See this running on ideone

    EDIT: Reading your comments in the other thread, I guess(?) you're interested in iterating over the inner tuples. You don't have to convert them to a list, you can simply iterate over them.

    import itertools
    animals = ['dog', 'cat']
    numbers = [5, 45, 8, 9]
    colors = ['yellow', 'blue', 'black']
    for triplet in itertools.product(animals, numbers, colors):
        for element in triplet:
            print element
    

    Demo on ideone

    EDIT 2: You can try that approach for your score thing.

    import itertools
    animals = ['dog', 'cat']
    numbers = [5, 45, 8, 9]
    colors = ['yellow', 'blue', 'black']
    general_list = ['horse', 'blue', 'dog', 45]
    
    def give_score(element):
        return 1 if element in general_list else 0
    
    for triplet in itertools.product(animals, numbers, colors):
        print sum([give_score(element) for element in triplet])
    

    Demo here

提交回复
热议问题