0

I need your help and I was hoping you can point me out to the right direction so I got a list of lists (this is just an example, the list of list can have more elements) and I was trying to get pairs of elements in the list

mylist = [[2, 3, 4], [2, 3]]

#desired output
# newlist = [[2,3], [3,4], [2,3]]

So in this question it helps creating a list of tuples in which each tuple is a pair, so I use the answers to this question to create this code

mylist = [[2, 3, 4], [2, 3]]

coordinates = []

for i in mylist:
    coordinates.append(list(map(list, zip(i, i[1:])))) #Instead of list of tuples, I use map to get a list of lists

print(coordinates)
#output [[[2, 3], [3, 4]], [[2, 3]]] #3D list  but not exactly what I want

a = [e for sl in coordinates for e in sl] #Use list comprehension to transform the 3D list to 2D list

print(a)
#output [[2, 3], [3, 4], [2, 3]] #My desired output

Using this code I get what a I want but I was wondering if there is simple way of achieving this without creating a bunch of auxiliary lists maybe with a simple list comprehension? But I can't figure it out how to do this, so any help would be appreciated, thank you!

2 Answers2

5

Try this:

mylist = [[3, 2, 4, 3], [3, 3, 1], [2, 1]]
res = [x[idx: idx+2] for x in mylist for idx in range(0, len(x) - 1)]
print(res)

Output:

[[3, 2], [2, 4], [4, 3], [3, 3], [3, 1], [2, 1]]
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
deadshot
  • 8,881
  • 4
  • 20
  • 39
1

You can use a nested list comprehension:

mylist = [[2, 3, 4], [2, 3]]
def get_groups(l, n):
  return [l[i:i+n] for i in range(len(l)-n+1)]

new_l = [i for b in mylist for i in get_groups(b, 2)]

Output:

[[2, 3], [3, 4], [2, 3]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102