'index values not updating to what I want them to be
I have the following code. I'm trying to iterate through List2 to find all the indices of Value. I then want to set the index in List1 to 0 for all the matching indices in List2.
List1 = [1, 1, 1, 0, 0, 1, 1, 1]
List2 = [[[3.08125597]], [[1.64528009]], [[1.64528009]], [[5.33474274e+26]], [[5.33474274e+26]], [[1.64528009]], [[1.64528009]], [[3.08125597]]]
Value = [[1.64528009]]
print(List1)
for m in range(len(List2)):
if List2[m] == Value[0]:
List1[m] = 0
print(List1)
Output
[1, 1, 1, 0, 0, 1, 1, 1]
[1, 1, 1, 0, 0, 1, 1, 1]
Index 1, 2, 5, 6 should all be updated to zero in List1. What am I doing wrong here?
Solution 1:[1]
Every item in your List2 appears to be it's own list of lists, (as does your Value). You'll need to either cut down on the brackets eg.
List1 = [1, 1, 1, 0, 0, 1, 1, 1]
List2 = [3.08125597, 1.64528009, 1.64528009, 5.33474274e+26, 5.33474274e+26, 1.64528009, 1.64528009, 3.08125597]
Value = 1.64528009
print(List1)
for m in range(len(List2)):
if List2[m] == Value:
List1[m] = 0
print(List1)
Or add some extra indexing eg.
List1 = [1, 1, 1, 0, 0, 1, 1, 1]
List2 = [[[3.08125597]], [[1.64528009]], [[1.64528009]], [[5.33474274e+26]], [[5.33474274e+26]], [[1.64528009]], [[1.64528009]], [[3.08125597]]]
Value = [[1.64528009]]
print(List1)
for m in range(len(List2)):
if List2[m][0][0] == Value[0][0]:
List1[m] = 0
print(List1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Linden |
