0

I have a list like below (similar to below but much longer)

[123.45, 32.89, 234.90, 234.96, 56.94, 71.21]

I wish to chop it up to look like this (I need the [ and ( brackets as per this below)

[(123.45, 32.89), (234.90, 234.96), (56.94, 71.21)]

I am not professional python programmer. I use a Visual Programming Language called DynamoBIM. I occasionally have to write a little bit of Python to do stuff with DynamoBIM.

sjmurphy84
  • 33
  • 4

3 Answers3

1

You can zip the list against itself, both striding by 2 but one list offset one index from the other.

>>> data = [123.45, 32.89, 234.90, 234.96, 56.94, 71.21]
>>> list(zip(data[::2], data[1::2]))
[(123.45, 32.89), (234.9, 234.96), (56.94, 71.21)]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

A space efficient way without slicing:

data = [123.45, 32.89, 234.90, 234.96, 56.94, 71.21]

i = iter(data)
[*zip(i, i)]
# [(123.45, 32.89), (234.9, 234.96), (56.94, 71.21)]

You can do it in one go in Python >= 3.8 using an assignment expression:

[*zip((i := iter(data)), i)]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • This is certainly cool, although it will only work in Python 3.8 or new (because of the walrus operator `:=`). –  Oct 28 '21 at 14:20
0

You can use a generator and itertools.islice:

from itertools import islice

l = [123.45, 32.89, 234.90, 234.96, 56.94, 71.21]
i = iter(l)
[tuple(islice(i,2)) for n in range(len(l)//2)]

output: [(123.45, 32.89), (234.9, 234.96), (56.94, 71.21)]

mozway
  • 194,879
  • 13
  • 39
  • 75