简体   繁体   中英

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

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM