Hey guys I’m using python and I was just wondering how we can make combinations of lists of specific lengths from an original list of elements? For example, I have an original list ["2H", "AH", "KH", "QH", "JH", "0H", "9H"], is there any way for me to create a final list where ALL of the new assorted lists of specific lengths (3 to 5) are contained?
Basically from the original list above, I want a returned list as shown below:
[['9H', '0H', 'JH'], ['0H', 'JH', 'QH'], ['JH', 'QH', 'KH'], ['QH', 'KH', 'AH'],
['KH', 'AH', '2H'], ['9H', '0H', 'JH', 'QH'], ['0H', 'JH', 'QH', 'KH'],
['JH', 'QH', 'KH', 'AH'], ['QH', 'KH', 'AH', '2H'], ['9H', '0H', 'JH', 'QH', 'KH'],
['0H', 'JH', 'QH', 'KH', 'AH'], ['JH', 'QH', 'KH', 'AH', '2H']]
Thanks!
Explanation
This solution builds on the use of
zip.This shows an example of how
zipworks, by taking an item from each of its paramters together.By starting at the 1st item of the same list as the second paramater you can get every 2 items.
Same for every 3 items.
To do this automatically you can use the
*(splat) to get the arguments ofzipfrom a list comprehension.In the example, the results come in reverse, so
reversedgives a reverse iterator through the list. To slice an iterator,islicefrom itertools must be used.islicetakes the iterable followed by the index to start the slice and the index to end it.Nonecan be used to go all the way to the end of the iterable.So that gives all the results for every 3 items. Now every 4 and 5 items are needed so this operation is performed for
range(3),range(4)andrange(5).This would give a generator with a list for each of
3,4, and5but they need to be all one list. They can be chained together withchain.from_iterablewith the result being converted to alist.