Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change list entries based on condition in python

I want to "draw a picture": I create a list with entries of o´s. Then I want to go through each element of the list to weigh a random number against a previously chosen ‘density’ number. If the number is smaller than my previously chosen density, then I want that entry to be replaced by a T.. Then it’s the next element’s turn with a new random number.

This is my code so far:
It either gives all o’s or just a single T.

import random

list = []
number_of_entries = 5
density = 0.5

list.append(["o"]*number_of_entries)  # ['o', 'o', 'o', 'o', 'o']

for index, entry in enumerate(list):
    if random.random() < density:    
        list[index] = "X"
     

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your variable list (by the way don’t use reserved words as variables names) has two nested lists and that’s the problem, try this:

import random

number_of_entries = 5
density = 0.5
alist = ["o"] * number_of_entries
for index, entry in enumerate(alist):
    if random.random() < density:
        alist[index] = "X"
        
print(alist)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading