Python displays a value for each i-th subnet element

I am trying to do the following in python: specify list of lists and integer i

input = [[1, 2, 3, 4], [1, 2, 3, 4], [5, 6, 7, 8]]
i = 1

I need to get another list that has all 1s for the elements of the i-th list, 0 otherwise

output = [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]

I wrote this code

output = []
for sublist in range(0, len(input)):
    for item in range(0, len(input[sublist])):
        output.append(1 if sublist == i else 0)

and it obviously works, but since I'm new to python, I believe there is a better “pythonic” way to do this.

I thought using mapmight work, but I can't get the list index with it.

+4
source share
2 answers

Creating an additional variable to get the index of the current element during the interaction is rather messy. A common alternative is to use a enumeratebuilt-in function.

. , , - , . () , enumerate(), , count ( , 0), , .

:

input_seq = [[1, 2, 3, 4], [1, 2, 3, 4], [5, 6, 7, 8]]
i = 1
o = [1 if idx == i else 0 for idx, l in enumerate(input_seq) for _ in l]

,

o = [int(idx == i) for idx, l in enumerate(input_seq) for _ in l]

- , , .

+4

1-, :

output = [int(j == i) for j, sublist in enumerate(input) for _ in sublist]

:

output = []
for j, sublist in enumerate(input):
    output.extend([int(i == j)] * len(sublist))

"0 1?" , .

+3

All Articles