Reputation: 1541
So I have a list of 6 variables. I want to separate that into 2 lists, one containing the elements to the left of a given variable, and the other containing everything to the right of that given variable. For example, if I have:
var1 = 25
var2 = 30
var3 = 35
var4 = 40
var5 = 45
var6 = 50
arr = [var1,var2,var3,var4,var5,var6]
I would like to separate at var 3, giving:
arr1 = [var1,var2]
arr2 = [var4,var5,var6]
It's kind of like using split(var3) on a string. I am successfully able to do this with the following code:
arrleft = arr[:arr.index(var3)]
arrreverse = sorted(arr, reverse=True)
arrcut = y[:y.index(var3)]
arrright = sorted(arrcut, reverse=False)
print arrleft
print arrright
However, this just seems like a poor method of doing it. Does anyone know an easier method?
Thanks.
Upvotes: 1
Views: 80
Reputation: 37103
arr = [25, 30, 35, 40, 45, 50]
arr1 = arr[:2]
arr2 = arr[2:]
print arr1, arr2
gives the result you want. However you actually seem to want a list of values < var3 and a list of values > var 3. One way of doing that (using an arbitrary 35 as a limit rather than a variable) would be
arr.sort()
index = sum(1 for x in arr if x < 35)
arr1 = arr[:index]
arr2 = arr[index:]
print arr1, arr2
This has the merit that the limit need not appear in the list. If you know it does then you could use
index = arr.find(35)
instead, as that will be quicker on long lists.
Upvotes: 0
Reputation: 1171
You should use the same approach for arrright as you did for arrleft.
Something like this should do it:
index = arr.index(var3)
arrleft = arr[:index]
arrright = arr[index + 1:]
Upvotes: 2
Reputation: 7555
What's wrong with this?
i = arr.index(var3)
left = arr[:i]
right = arr[i+1:]
Upvotes: 6