2

I want to create two lists based on sorted_bounds with every other tuple.

bounds = [1078.08, 1078.816, 1078.924, 1079.348, 1079.448, 1079.476]
sorted_bounds = list(zip(bounds,bounds[1:]))
print(sorted_bounds)
# -> [(1078.08, 1078.816), (1078.816, 1078.924), (1078.924, 1079.348), (1079.348, 1079.448), (1079.448, 1079.476)]

Desired output:

list1 = [(1078.08, 1078.816), (1078.924, 1079.348), (1079.448, 1079.476)]  
list2 = [(1078.816, 1078.924), (1079.348, 1079.448)]

How would I do this? I am completely blanking.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
dfahsjdahfsudaf
  • 461
  • 4
  • 11
  • Hi, not sure if this might be of interest https://stackoverflow.com/questions/1624883/alternative-way-to-split-a-list-into-groups-of-n – IronMan Sep 16 '20 at 22:53

2 Answers2

3
list1 = sorted_bounds[0::2]
list2 = sorted_bounds[1::2]

The third value in brackets is "step", so every second element in this case.

Andrew Morozko
  • 2,576
  • 16
  • 16
1

Trying to think of a way of doing this in a single pass, but here's a clean way to do it in two passes:

list1 = [x for i, x in enumerate(sorted_bounds) if not i % 2]
list2 = [x for i, x in enumerate(sorted_bounds) if i % 2]
print(list1)
print(list2)

Result:

[(1078.08, 1078.816), (1078.924, 1079.348), (1079.448, 1079.476)]
[(1078.816, 1078.924), (1079.348, 1079.448)]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
CryptoFool
  • 21,719
  • 5
  • 26
  • 44