Learn4life
Learn4life

Reputation: 227

Split a list in for loop based on indices of list

This is a simplified version of some code im working on, a kind of toy model so i can focus only on the bit thats troubling me. This is why i have a function defined for finding the minimum, rather than simply using the numpy command. In my proper code, a fucntion is required, since its not as simple as using a pre-existing numpy function.

What i want to do is split my list into 2 list at the minimum point - so given what i have here, i would ideally get [15, 62, 49, 49, 4] and [100, 71, 16, 70, 62] . HOwever, i dont get this. I get all the points stored in node1, and nothing in node2. i really cant figure out why - as you can see, ive tried 2 ways of doing the for loop. i know completely the idea of the code, that the loop should run over the indices of the list and then store the values of these indices in the new lists, node1 and node2. what am i doing wrong?

#generate random list of numbers
import random
randomlist = [] #==profile_coarse
for i in range(0,10):
    n = random.randint(1,100)
    randomlist.append(n)
print(randomlist)

#define a function to find minimum
def get_min(list):
    mini=np.min(randomlist)
    return mini

node1=[]
node2=[]

for i in enumerate(randomlist):
    if i<=get_min(randomlist):
        node1.append(randomlist[i])
    else:
        node1.append(randomlist[i])
#OR

for i in range(0,len(randomlist)):
    if i<get_min(randomlist):
        node1.append(randomlist[i])
    else:
        node1.append(randomlist[i])

print(node1,node2)

which yields

[15, 62, 49, 49, 4, 100, 71, 16, 70, 62] []

Upvotes: 2

Views: 49

Answers (2)

kederrac
kederrac

Reputation: 17322

you could use the built-in functions enumerate and min:

randomlist = [15, 62, 49, 49, 4, 100, 71, 16, 70, 62]

#define a function to find minimum
def get_min(l):
    mini= min(enumerate(l), key=lambda x: x[1])
    return mini
index_min, min_val = get_min(randomlist)
node1 = randomlist[:index_min + 1]
node2 = randomlist[index_min + 1:]

print(node1, node2)

print(node1)
print(node2)

output:

[15, 62, 49, 49, 4] [100, 71, 16, 70, 62]

Upvotes: 2

Verma
Verma

Reputation: 966

enumerate returns a tuple of a a counter (by default starting at 0) and the one value from the iterable you are passing.

In your code i would be (0, 15), (1, 62)... etc.

My guess is that you simply want to do for i in randomlist

Keep in mind using a min function will in any case put all the values in one node and not in 2 as you want it to do.

Upvotes: 2

Related Questions