Generating all combinations of a list in python

后端 未结 7 2120
不思量自难忘°
不思量自难忘° 2020-11-27 19:29

Here\'s the question:

Given a list of items in Python, how would I go by to get all the possible combinations of the items?

There are several similar questio

相关标签:
7条回答
  • 2020-11-27 20:14

    You can generate all the combinations of a list in python using this simple code

    import itertools
    
    a = [1,2,3,4]
    for i in xrange(1,len(a)+1):
       print list(itertools.combinations(a,i))
    

    Result:

    [(1,), (2,), (3,), (4,)]
    [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
    [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
    [(1, 2, 3, 4)]
    
    0 讨论(0)
提交回复
热议问题