简体   繁体   中英

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]

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 .

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

如果您的 S 列表使用基于 1 的索引

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM