Breno Baiardi Breno Baiardi - 1 year ago 28
Python Question

List slicing given a specific range

First of all thank you for seeing this question, and please, there's gotta be a simpler way to solve this problem.
I have two lists, which I call v1 and v2, and they have different ranges:

250-1100 and 900 1700

I want to slice them within the range as 900-950. So BOTH of them, should have their inferior part sliced until the minimum value is 900, and the superior part sliced until the maximum value is 950.

NOTE: v1 and v2 are being referenced with double indexes [i][0] because they are pairs of data, and I am slicing the lists by the first value (they actually are {x,y} pairs).

I have this method which I am using to handle it:

def corte(v1, v2):
for i in range(len(v1)):
if i == 0 and v1[0][0] == v2[0][0]:
if v1[i][0] >= v2[0][0]:
v1 = v1[i:]

if i == len(v2) and v1[-1][0] == v2[-1][0]:
return v1, v2

if v1[-1][0] > v2[-1][0]:
i = len(v1)
while i > 0:
i -= 1
if v1[i - 1][0] <= v2[-1][0]:
v1 = v1[:i]
i = len(v2)
while i > 0:
i -= 1
if v2[i - 1][0] <= v1[-1][0]:
v2 = v2[:i + 1]
return v1, v2

My biggest issue is being the treatment of this range thing. I know it is too much to understand and the problem may seem a little confusing, so what I ask is some advice, maybe any ways you think I should try to make this better.




would return v=[900,0],[900.1,0],[920.0,0],[935,0],[945,0],[949.1,0]

the second element is not relevant to the problem.

EDIT: actually this code is not slicing it acordingly to the 900-950 range, it is removing the excess of values when I match the edge of one list with the other.

Answer Source

You need concrete examples of input and output desired, but I think you want a list comprehension. For example, this will return the values in v1 where the first element of the pair is in the range 900-950.

[pair for pair in v1 if 900 <= pair[0] <= 950]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download