Learning Python
Learning Python

Reputation: 1

python double iterator in list comprehension

so if I have 1's in all the indexes position of S and rest would be 0's. Length of the new string will be N. How do I do that in Python list comprehension

S= [2,5,8]
N= 10
Desired output: [0,1,0,0,1,0,0,1,0,0]

My Code:

newlist = [1 if x.__index__() == S[i]  else 0 for i in range(len(S)) for x in range(N)]

My Output: [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]

Upvotes: 0

Views: 130

Answers (3)

Jacob
Jacob

Reputation: 810

If your S list is using 1-based indexing

[int(i in S) for i in range(1, N+1)]

Upvotes: 0

Max Shouman
Max Shouman

Reputation: 1331

output = [1 if i+1 in S else 0 for i in range(N)]

Upvotes: 1

kaya3
kaya3

Reputation: 51063

The straightforward solution is not using a list comprehension:

result = [0] * N
for i in S:
    result[i - 1] = 1

Note that i - 1 is needed to convert the 1-based indices in your list S to 0-based indices. If you have 0-based indices in your list (which would be simpler for most purposes), then you can just write result[i] = 1.

Upvotes: 1

Related Questions