How to create pairs in python list . list = [1,2,3,4,5,6,7] i want to compare (1,2),(3,4) (5,6)
identical pairs comparison
how can we loop through all the pairs
How to create pairs in python list . list = [1,2,3,4,5,6,7] i want to compare (1,2),(3,4) (5,6)
identical pairs comparison
how can we loop through all the pairs
You can use zip
and slice the input list every two items with different starting points:
lst = [1,2,3,4,5,6,7]
list(zip(lst[::2], lst[1::2]))
output: [(1, 2), (3, 4), (5, 6)]
If I understand you correctly, you want to take the list and create all possible pairs. To do that, you should use itertools.
Take a look at the following topic: How to split a list into pairs in all possible ways.
import itertools
list(itertools.combinations(range(6), 2))
#[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
you could do something like this:
list = [1,2,3,4,5,6,7]
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):yield lst[i:i + n]
sublist = [x for x in chunks(list, 2)]
for x in sublist:
if x.__len__() > 1:continue
else:sublist.remove(x)
print(sublist)
Output:
[[1,2],[3,4],[5,6]]
It will use a moving cursor for slicing to get the value.
def func(l):
prev_i, i = 0, 2
while True:
current = l[prev_i: i]
if len(current) < 2:
break
yield current
prev_i, i = i, i + 2
print(list(func([1,2,3,4,5,6,7])))
Output:
[[1, 2], [3, 4], [5, 6]]