DEV Community

artem
artem

Posted on

1 2

Избавляемся от вложенных циклов с itertools.product

Если у нас есть небольшие массивы данных, по вариациям которых нужно пройтись, чтобы не использовать вложенный цикл можно использовать itertools.product.

Представим

colors = ['black', 'white', 'yellow']
animals = ['rabbit', 'shark', 'quokka']

Дефолт код, для прохода по всем комбинациям из массивов

for color in colors:
  for animal in animals:
    print(f'{color} {animal}')

сокращается с itertools

import itertools

for color, animal in itertools.product(colors, animals):
  print(f'{color} {animal}')

и как бонус однострочник

[print(f'{color} {animal}') for color, animal in itertools.product(colors, animals)]

как минус - создается новый объект, поэтому для больших объемов данных нецелесообразно
как плюс - в качестве аргументов можно передать любое количество массивов - получим все их комбинации

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay