-1

I'm trying to randomly split a list X with len(X) = 150 into two lists X_train and X_test with len(X_train) = 105 and len(X_test) = 45.

split = np.random.choice(150, 105)
X_train = [X[i] for i in split]
X_test = [X[i] for i not in split]

But in line 3 I get a SyntaxError.

How would I do this correctly?

dYTe
  • 191
  • 1
  • 8

2 Answers2

0

You can achieve that by

split = random.sample(range(len(X)), 105)
X_train = [X[i] for i in split]
X_test = [X[i] for i in [i for i in [i for i in range(len(X)) if i not in split]]]

That will create you a list of a random unique number of 105 items and will and then it will extract to X_train all the randoms number indexes and to X_test it will extract all the 45 number that not in the split list.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
0

If you have a list to split you could just slice it

from random import randint

a = [1,2,3,4,5,6,7,8,9,10]
s = randint(0, len(a))
print(a[:s])
print(a[s:])
Tony
  • 9,672
  • 3
  • 47
  • 75