Home > Software engineering >  Adding condition in list in python
Adding condition in list in python

Time:10-11

I do not how to add extra conditions to this code.

(With only using randint)

For example with list [1, 2, 3, 4, 0] I need to generate random number expect the last one(covered in my code) but the next condition is, it can not choose a index number which value is 0. So for list [3, 3, 0, 3, 3, 7] it can only indexes 0,1,3,4(not 2 and 5 because I can not include the last number and index with value0).

My code so far:

import random

our =[ 2, 3, 4, 0]

random_index = random.randint(0,len(our)-2)

random_number = our[random_index]

print(random_number)

I will be very glad for any help.

CodePudding user response:

You can create a second list that stores the valid index values.

import random

our = [3, 3, 0, 3, 3, 7]

index = []

for i in range(0, len(our)-1) :
    if our[i] != 0 :
        index.append(i)

# index: [0, 1, 3, 4]

random_index = random.choice(index)

EDIT: You can perform a sanity check for a non-zero value being present.

The any() function returns True if any element of an iterable is True. 0 is treated as False and all non-zero numbers are True.

valid_index = any(our[:-1])

if valid_index:
    index = []
    for i in range(0, len(our)-1) :
        if our[i] != 0 :
            index.append(i)

CodePudding user response:

You can use a while loop to check if the number equals 0 or not.

import random


our = [3, 6, 2, 0, 3, 0, 5]

random_number = 0
while random_number == 0:
    random_index = random.randint(0, len(our)-2)
    random_number = our[random_index]

print(random_number)
  • Related