[英]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] [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)] [(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 但它给出了所有可能的组合,而不仅仅是数字邻居。
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.使用
zip()
将列表的一部分偏移一个位置。
result = list(zip(newl, newl[1:]))
Just use this simple for loop:只需使用这个简单的 for 循环:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.