Mohammad
Mohammad

Reputation: 1098

How to use tuples to slice a list?

I have generated a list of tuples using the combination function in itertools package. How can I pass that to a list of integers to slice it? Here is my sample code, but gives me an error because of the tuple:

from itertools import combinations
myNumbers = [12,4,5,6,7,9,3,2]
listOfIndexes = list(range(8))
comb = combinations(listOfIndexes, 3)
for i in list(comb):
    print(myNumbers[int(i)])

my expected output is to print all combinations of 3 numbers in myNumbers, such as:

12,4,5
4,5,6
5,6,7
...

Upvotes: 1

Views: 67

Answers (3)

sahasrara62
sahasrara62

Reputation: 11228

from itertools import combinations
myNumbers = [12,4,5,6,7,9,3,2]
listOfIndexes = list(range(8))
comb = combinations(listOfIndexes, 3)
for i in list(comb):    
    print(*[myNumbers[ij] for ij in i],sep=',')

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

Based on the sample output, it looks like you aim to print all consecutive three elements of the list. This is something different, and we do not need combinations for that.

We can slice the list with:

myNumbers = [12,4,5,6,7,9,3,2]
for i in range(len(myNumbers)-2):
    print(myNumbers[i:i+3])

or we can print the items with a comma as separator with:

myNumbers = [12,4,5,6,7,9,3,2]
for i in range(len(myNumbers)-2):
    print(*myNumbers[i:i+3], sep=',')

This then prints:

>>> for i in range(len(myNumbers)-2):
...     print(*myNumbers[i:i+3], sep=',')
... 
12,4,5
4,5,6
5,6,7
6,7,9
7,9,3
9,3,2

Upvotes: 1

JacobIRR
JacobIRR

Reputation: 8946

this works:

from itertools import combinations
myNumbers = [12,4,5,6,7,9,3,2]
listOfIndexes = list(range(8))
comb = combinations(listOfIndexes, 3)
for i in list(comb):
  a,b,c = myNumbers[i[0]], myNumbers[i[1]], myNumbers[i[2]]
  print(a,b,c)

... but as far as I can tell, the above code just does this in a less efficient way:

print([i for i in combinations(myNumbers, 3)])

Upvotes: 1

Related Questions