-1

I'm trying to generate a list with a variable that I can control. So let's say I want to generate a list of length 100 with conditions:

[True if x > 0.8 else False for x in [random_number_between_0_and_1]]

So the list will have 2:8 True/False values, and so on. I tried something like this but my syntax is off:

    my_list = []
    True if x > 0.8 else False for x in random()
    my_list.append(i)

Any help is appreciated!

mlenthusiast
  • 1,094
  • 1
  • 12
  • 34
  • 1
    Take a look at [`random()`](https://docs.python.org/3/library/random.html#random.random) function and how to write a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) in Python. – Vasilis G. Mar 04 '20 at 22:46
  • Does this answer your question? [A weighted version of random.choice](https://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice) – AMC Mar 05 '20 at 01:38

3 Answers3

2

Use random.choices.

my_list = random.choices([True, False], weights=[2, 8], k=100)
chepner
  • 497,756
  • 71
  • 530
  • 681
1

I just went ahead and made this short module for you:

import random

def main():
    my_list = []
    for _ in range(100):
        # Ternary statement like your example
        x = True if random.random() > 0.8 else False
        my_list.append(x)

    print(my_list)

if __name__ == "__main__":
    # Run main functionality
    main()

This goes ahead and achieves what you were trying to do for 100 iteration. Go ahead and change the number for further iterations :)

NolanRudolph
  • 106
  • 11
1

range(100) will return a sequence of 100 elements that you can loop over. For each of them, call rand() and return the condition result into the list comprehension.

my_list = [random() > 0.8 for _ in range(100)]

There's no need to use True if ... else False, since the result of a comparison is True or False.

Barmar
  • 741,623
  • 53
  • 500
  • 612