Reputation: 915
I have a list (aList) I need to create another list of the same length as aList (checkColumn) and add 1 at the positions defined in the index list (indexList), the positions not defined in the indexList should be 0
Input:
aList = [70, 2, 4, 45, 7 , 55, 61, 45]
indexList = [0, 5, 1]
Desired Output:
checkColumn = [1,1,0,0,0,1]
I have been experimenting around with the following code, but I get the output as [1,1]
for a in len(aList):
if a == indexList[a]:
checkColumn = checkColumn[:a] + [1] + checkColumn[a:]
else:
checkColumn = checkColumn[:a] + [0] + checkColumn[a:]
I have tried with checkColumn.insert(a, 1) and I get the same result. Thanks for the help!
Upvotes: 1
Views: 76
Reputation: 56
Would this help?
First, you initialize checkColumn with 0
checkColumn = [0] * len(aList)
Then, loop through indexList and update the checkColumn
for idx in indexList:
checkColumn[idx] = 1
Cheers!
Upvotes: 3
Reputation: 25362
You could do this in one line using a list comprehension:
aList = [70, 2, 4, 45, 7 , 55, 61, 45]
indexList = [0, 5, 1]
checkColumn = [1 if a in indexList else 0 for a in range(len(aList))]
print(checkColumn)
# [1, 1, 0, 0, 0, 1, 0, 0]
Upvotes: 2