How would I go about extracting coordinates from a list skipping one value?

Viewed 68

I need to extract coordinate values out of this list in the below manner.

input: [[2, 0, 4, 6], [3, 0, 4, 6]]

output: [[(2, 4), (0, 6)] , [(3, 4), (0, 6)]]

so far I tried this code:

pathlist = [[2, 0, 4, 6], [3, 0, 4, 6], [1, 0, 4, 6], [2, 0, 4, 6]]

j = 0
k = 2
paths = []
for i in pathlist:
    for x in range(len(pathlist)-2):
        paths.append((i[j],i[k]))
        j += 1
        k += 1

But this keeps throwing an index error that I can't quite figure out and I'm not sure if the code is on the right track. in python 3.6

5 Answers

Use list unpacking inside a list comprehension:

list_ = [[2, 0, 4, 6], [3, 0, 4, 6]]

[[(x1, y1), (x2, y2)] for x1, x2, y1, y2 in list_]

It's good practice to give things (individual coordinate values in this case) an explicit name as soon as possible.

This gives you the output your looking for:

pathlist = [[2, 0, 4, 6], [3, 0, 4, 6], [1, 0, 4, 6], [2, 0, 4, 6]]

paths = [[(i[0], i[2]), (i[1], i[3])] for i in pathlist]

print(paths)
# [[(2, 4), (0, 6)], [(3, 4), (0, 6)], [(1, 4), (0, 6)], [(2, 4), (0, 6)]]
a = [[2, 0, 4, 6], [3, 0, 4, 6]]
res = []
for l in a:
  res.append([tuple(l[0::2]), tuple(l[1::2])])

print(res)

try with this

Just move initial sentence j = 0 and k = 2 into the first loop. And update pathlist to i in second loop, IIUC.

pathlist = [[2, 0, 4, 6], [3, 0, 4, 6], [1, 0, 4, 6], [2, 0, 4, 6]]

paths = []
for i in pathlist:
    j = 0
    k = 2
    for x in range(len(i)-2):
        paths.append((i[j],i[k]))
        j += 1
        k += 1

1st mistake-> initialise j and k inside for loop. 2nd mistake -> take a temp array and append updated temp inside paths

pathlist = [[2,0,4,6],[3,0,4,6],[7,9,5,2]]
path = []
for i in pathlist:
    j = 0 
    k = 2 
    temp = []
    for x in range(len(i)-2):
        temp.append((i[j],i[k]))
        j =+ 1
        k =+ 1
    paths.append(temp)
print(paths)
Related