Python map a value to each i-th sublist's element -
i'm trying following in python: given list of lists , integer i
input = [[1, 2, 3, 4], [1, 2, 3, 4], [5, 6, 7, 8]] = 1
i need obtain list has 1s elements of i-th list, 0 otherwise
output = [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
i wrote code
output = [] sublist in range(0, len(input)): item in range(0, len(input[sublist])): output.append(1 if sublist == else 0)
and works, since i'm newbie in python suppose there's better 'pythonic' way of doing this.
i thought using map
work, can't index of list it.
creating variable index of current element in interation quite unpythonic. usual alternative usage of enumerate
built-in function.
return enumerate object. sequence must sequence, iterator, or other object supports iteration. next() method of iterator returned enumerate() returns tuple containing count (from start defaults 0) , values obtained iterating on sequence.
you may use list comprehension double loop inside concise 1 liner:
input_seq = [[1, 2, 3, 4], [1, 2, 3, 4], [5, 6, 7, 8]] = 1 o = [1 if idx == else 0 idx, l in enumerate(input_seq) _ in l]
alternatively,
o = [int(idx == i) idx, l in enumerate(input_seq) _ in l]
underscore throwaway name, since in case don't care actual values stored in input sublists.
Comments
Post a Comment