-1

I have the following list :

all_lines [[(0, 0), (0, 7)], 
           [(20, 20), (0, 7)], 
           [(0, 0), (13, 20)], 
           [(20, 20), (13, 20)], 
           [(10, 0), (0, 17), (10, 10), (10, 17), (20, 0), (20, 17), (0, 20), (20, 7)]]

So I would like to convert it to the following format:

all_lines [[(0, 0), (0, 7)], 
           [(20, 20), (0, 7)], 
           [(0, 0), (13, 20)], 
           [(20, 20), (13, 20)], 
           [(10, 0), (0, 17)], 
           [(10, 10), (10, 17)], 
           [(20, 0), (20, 17)], 
           [(0, 20), (20, 7)]]

I tried :

flat_list = [item for sublist in all_lines for item in sublist]

but did not give me desired format.

How can I convert the list into my desired format?

Georgy
  • 12,464
  • 7
  • 65
  • 73
ash
  • 55
  • 5
  • 1
    Your problem is that what your example shows is *not* flattening -- so using a flattening comprehension will not get what you want. What you're trying to do is "chunking", and selectively so. You're chunking each element into lists of length 2 -- and only the last list is not already in that format. With that hint I expect you can find and implement something that's closer to what you describe. AT the very least, you could *fully* flatten the list, and then chunk the remaining "simple" list of tuples. – Prune Apr 01 '20 at 01:01
  • 1
    One approach is after you have flat_list, create pairs from it as follows: `desired_list = [flat_list[i:i+2] for i in range(0, len(flat_list), 2)]` – DarrylG Apr 01 '20 at 01:07

1 Answers1

0

Using nested list comprehension works for your purpose:

flat=[[all_lines[i][j],all_lines[i][j+1]] for i in range(0,len(all_lines)) for j in range(0,len(all_lines[i]),2) ]

The assumption here is that the length of any element is divisible by 2.

jpf
  • 1,447
  • 12
  • 22