Rakesh Adhikesavan
Rakesh Adhikesavan

Reputation: 12816

How to generate a list with one specific element as 1 and the rest as 0?

I wish to generate m = 10 lists of fixed size n = 5

Condition: I have a list z of length m

z = [0, 4, 3, 2, 4, 1, 3, 2, 1, 0]

The above list contains the indices of the elements that should be 1. The program should generate

[1,0,0,0,0] # element at index 0 is 1, rest are 0 as dictated by condition list z 
[0,0,0,0,1] # element at index 4 is 1, rest are 0 
[0,0,0,1,0] # element at index 3 is 1, rest are 0 
[0,0,1,0,0] # element at index 2 is 1, rest are 0 
.
.

Upvotes: 1

Views: 898

Answers (2)

heemayl
heemayl

Reputation: 41987

You can do:

>>> z = [0, 4, 3, 2, 4, 1, 3, 2, 1, 0]

>>> for i in z:
...     x = [0] * 5
...     x[i] = 1
...     print(x)
... 
[1, 0, 0, 0, 0]
[0, 0, 0, 0, 1]
[0, 0, 0, 1, 0]
[0, 0, 1, 0, 0]
[0, 0, 0, 0, 1]
[0, 1, 0, 0, 0]
[0, 0, 0, 1, 0]
[0, 0, 1, 0, 0]
[0, 1, 0, 0, 0]
[1, 0, 0, 0, 0]

Upvotes: 0

Akshat Mahajan
Akshat Mahajan

Reputation: 9846

output = [[1 if i == j else 0 for i in xrange(n)] for j in z]

This list comprehension will create an array of arrays with the pattern you seek. How you choose to flatten this list is upto you.

Alternatively, you can wrap this up in a generator, and yield each individual array as you iterate through it. It takes a simple change:

output = ([1 if i == j else 0 for i in xrange(n)] for j in z)

and then you can simply iterate through the arrays as follows:

for array in output:
    # do something 

Upvotes: 4

Related Questions