Is there a function in Python's standard library that does something similar to the loop function?
I was looking for a function to loop through a list of lists that would automatically put the results together and yield each result produced by the (internal) loops. Not seeing any recognizable candidates from Python's standard library, the loop
function below was the result. Does anyone know of any available function that does something similar or is 开发者_JAVA技巧written in a far better way that can be used instead of loop
? The order of the yielded iterations does not matter in the example usage of the code given below, but for general use in other projects, it probably would be best that yields come out in the order lists go into it.
from itertools import permutations
GROUPS = ('he', 'she'), ('man', 'woman'), ('male', 'female'), ('adam', 'eve')
def main():
for size in range(2, len(GROUPS) + 1):
for groups in permutations(GROUPS, size):
for items in loop(*groups):
print(''.join(items).capitalize())
def loop(*args):
head, tail = args[0], args[1:]
if tail:
for a in head:
for b in loop(*tail):
yield [a] + b
else:
for a in head:
yield [a]
if __name__ == '__main__':
main()
itertools.product(*groups)
精彩评论