Reputation: 503
I have lists like this:
testList = [[(0.0, -0.9960135495794032), (0.5, -1.0), (2.0, -0.16138322487766676), (2.5, 1.0849272141417852)],
[(4.0, 3.3149805356833015), (4.5, 0.1649293864654484), (5.0, -1.0), (5.5, 0.33841349597101744), (6.0, 4.702347949145297)],
[(88.5, 3469038127.7763767), (89.0, 1309004102.449714), (90.0, -1.0)]]
I am trying to slice the lists based on the second index in the tuple, for example, I would like the cut each of the lists into two parts at the point when the tuple is (x, y=-1).
This is the result I am trying to get:
[[(0.0, -0.9960135495794032), (0.5, -1.0)], [(0.5, -1.0), (2.0, -0.16138322487766676), (2.5, 1.0849272141417852)]]
[[(4.0, 3.3149805356833015), (4.5, 0.1649293864654484), (5.0, -1.0)], [(5.0, -1.0), (5.5, 0.33841349597101744), (6.0, 4.702347949145297)]]
[[(88.5, 3469038127.7763767), (89.0, 1309004102.449714), (90.0, -1.0)], [(90.0, -1.0)]]
How can I make it?
Upvotes: 1
Views: 71
Reputation:
In the first two cases, when you split, you put the (x,y) couple where you split in both parts. For consistency I do the same for the third (hence the second part is not empty). But it's easy to adapt.
testList = [
[(0.0, -0.9960135495794032), (0.5, -1.0), (2.0, -0.16138322487766676), (2.5, 1.0849272141417852)],
[(4.0, 3.3149805356833015), (4.5, 0.1649293864654484), (5.0, -1.0), (5.5, 0.33841349597101744), (6.0, 4.702347949145297)],
[(88.5, 3469038127.7763767), (89.0, 1309004102.449714), (90.0, -1.0)]
]
def find_y(a, val):
for i, (x, y) in enumerate(a):
if y == val:
return i
return -1
def split_y(a):
k = find_y(a, -1)
if k < 0:
return a, []
else:
return a[:k + 1], a[k:]
for i, u in enumerate(testList):
l, r = split_y(u)
print("left%d = %s" % (i + 1, l))
print("right%d = %s" % (i + 1, r))
Cautionary note: usually it's a very bad idea to test floating point values for equality. A more robust test could be for instance:
def approx_eq(a, b, eps=1e-8):
return abs(a - b) < eps * max(abs(a), abs(b))
Upvotes: 2
Reputation: 20669
You can try this.
def c_slice(lst):
for slst in lst:
start = 0
for idx,(_,y) in enumerate(slst):
if y == -1:
yield [slst[start:idx+1], slst[idx:]]
break
Output:
out = list(c_slice(testList))
print(out[0])
#[[(0.0, -0.9960135495794032), (0.5, -1.0)],
# [(0.5, -1.0), (2.0, -0.16138322487766676), (2.5, 1.0849272141417852)]]
print(out[1])
#[[(4.0, 3.3149805356833015), (4.5, 0.1649293864654484), (5.0, -1.0)],
# [(5.0, -1.0), (5.5, 0.33841349597101744), (6.0, 4.702347949145297)]]
print(out[2])
#[[(88.5, 3469038127.7763767), (89.0, 1309004102.449714), (90.0, -1.0)],
# [(90.0, -1.0)]]
Upvotes: 2