2

model = [random.randint(0,1) if model.count(0) < 20 else 1 for _ in range(40)]

Of course model.count(0) is wrong. Here we go for right code, but w/o list comprehension.

model = list()
for i in range(40):
   if model.count(0) < 20:
       model.append(random.randint(0,1))
   else:
       model.append(1)

I'm just love list comprehensions it makes me easier to work with NLP and massives. So it would be cool to find new features.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Daniel Fedrain
  • 31
  • 1
  • 1
  • 4

1 Answers1

6

List Comprehension are good, but they are not suitable for all the scenarios. In your case, writing an explicit for loop makes more sense.

However, you may use random.shuffle in order to get the similar result more efficiently. If you need both 0 and 1 to be 20 in count in the resultant list, you can do:

>>> import random
>>> my_list = [0]*20 + [1]*20

>>> random.shuffle(my_list)
>>> my_list
[0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0]

However if you want the count of 0 to be random between 0-20 (which your current code is doing), then you may modify the above logic a little like:

>>> zero_count = random.randint(0, 20)
>>> one_count = 40 - zero_count

>>> my_list = [0]*zero_count + [1]*one_count
>>> random.shuffle(my_list)
>>> my_list
[1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126