Home > database >  Is there a way to create the possible pairs for number neighbors in python?
Is there a way to create the possible pairs for number neighbors in python?

Time:11-15

I'm attempting to create a new list with all the possible pairs in a list but only want to have the numbers that are neighbors be possible pairs.

For example, I have already created this list from a file:

[1, 8, 10, 16, 19, 22, 27, 33, 36, 40, 47, 52, 56, 61, 63, 71, 72, 75, 81, 81, 84, 88, 96, 98, 103, 110, 113, 118, 124, 128, 129, 134, 134, 139, 148, 157, 157, 160, 162, 164]

Im trying to create a list that outputs like this:

[(1,8), (8,10), (10,16), (16, 19), (19, 22), (22, 27), (27, 33), (33, 36), (36, 40), (40, 47), (47, 52), (52, 56), (56, 61), (61, 63), (63, 71), (71, 72), (72, 75), (75, 81), (81, 81), (81, 84), (84, 88), (88,96) .... (162, 164)]

I was attempting to use the import itertools but that is giving be all the possible combinations not just the number neighbors.

import itertools
for A, B in itertools.combinations(newl, 2):
            print(A, B)

CodePudding user response:

Use zip() with a slice of the list offset by one place.

result = list(zip(newl, newl[1:]))

CodePudding user response:

Just use this simple for loop:

newl = [1, 8, 10, 16, 19, 22, 27, 33, 36, 40, 47, 52, 56, 61, 63, 71, 72, 75, 81, 81, 84, 88, 96, 98, 103, 110, 113, 118, 124, 128, 129, 134, 134, 139, 148, 157, 157, 160, 162, 164]

lst = []

for i in range(len(newl)):
    try:
        lst.append((newl[i], newl[i 1]))
    except:
        pass
  • Related