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
  • 3

3 Answers3

2

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
  • 107,498
  • 14
  • 145
  • 201
2

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
  • 67,685
  • 6
  • 55
  • 77
  • This is certainly cool, although it will only work in Python 3.8 or new (because of the walrus operator `:=`). – richardec Oct 28 '21 at 14:20
1

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
  • 81,317
  • 8
  • 19
  • 49