0

I have the following list of events that have a binary outcome (i.e. 1 or 0):

events=['A', 'B', 'C']
outcomes=[True,False]

in each scenario, only one of these outcomes can be True. Is there a way to get an array like:

array=([True,False,False],[False,True,False], [False,False,True])

i know i can use itertools product with repeat but this will produce unwanted scenarios like [True,True,True] etc. in the array. ideally i would not have to filter it down as i expect my 'events' list to be much longer than the above.

Any one have any ideas? I can have 1 or 0 values in the array instead, I am not fussed.

1 Answer 1

0

You could create a generator to do it yourself.

def one_true(length):
    i = 0
    while i < length:
        lst = [False] * length
        lst[i] = True
        yield lst
        i +=1

print(list(one_true(3)))

This seems fairly trivial since your True just needs to "crawl" across the array.

If you want to include a case where they are all False just add yield [False] * length at the end.

def one_true(length):
    i = 0
    while i < length:
        lst = [False] * length
        lst[i] = True
        yield lst
        i +=1
    yield [False] * length

print(list(one_true(3)))

And from your example:

events = ['A', 'B', 'C']
print(list(one_true(len(events))))

Or if you want to be more concise you could use a comprehension with a custom function.

def insert_true(lst, index):
    lst[index] = True
    return lst
events = ['A', 'B', 'C']
length = len(events)
foo = [insert_true([False] * length, i) for i in range(length)]

print(foo)
Sign up to request clarification or add additional context in comments.

1 Comment

worked a charm, thanks! used the insert_true function. this also looks to work in case interested, answer to similar question: stackoverflow.com/questions/65374372/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.