开发者

using itertools to reduce the complexity of four "for" stmt?

I have list 4 lists:

list1, list2, list3, list4 = range(0,4), range(4,9), range(8,15), range(2,16)
# just using range() generate sample data  

I can list all the items combination by sequence list1_item, list2_item, list3_item, list4_item via below code:

for item1 in list1:
    for item2 in list2:
        for item3 in list3:
    开发者_C百科         for item4 in list4:
                   print [item1, item2, item3, item4]

May I know if I can do this job via itertools module?

Thanks


Yes, you can:

for n in itertools.product(list1, list2, list3, list4):
    print n

(n will be a tuple instead of a list).


I think what you want is itertools.product

import itertools
ret = list ( itertools.product( list1, list2, list3, list4 ) )

And ret is the result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜