Reputation: 1313
So i have a list of heights:
heights = [1, 2, 3, 5, 7, 8, 8, 13]
And im using this function to store each height integer value and its index in the list in a class i called Node.
def initializeNodes(heights):
ans = []
for height in heights:
ans.append(Node(heights.index(height), height))
return ans
But my problem is, because their are two 8's in the list, its giving them both the same first 8 position of 5 in the list:
0 1
1 2
2 3
3 5
4 7
5 8
5 8
7 13
How can i go around this? Thanks!
Upvotes: 2
Views: 104
Reputation: 4020
The problem is that you're generating the index from the values, why not do it the other way around?
heights = [1, 2, 3, 5, 7, 8, 8, 13]
def initializeNodes(heights):
ans = []
for index in range(len(heights)):
ans.append(Node(index, heights[index]))
return ans
This creates a list from 0 to the length of heights, and then will append the index then the height at this index.
Upvotes: 0
Reputation: 251186
The problem with list.index
is that it'll only return the index of first occurrence of the item.
>>> heights = [1, 2, 2, 3, 5, 5, 7, 8, 8, 13]
>>> heights.index(2)
1
>>> heights.index(5)
4
>>> heights.index(8)
7
help on list.index
:
L.index(value, [start, [stop]]) -> integer -- return first index of value.
You can do provide a different start
value to list.index
than 0, to get the index of repeated items:
>>> heights.index(5,heights.index(5)+1) #returns the index of second 5
5
But that is very cumbersome, a better solution as @MartijnPieters already mentioned is enumerate
Upvotes: 1
Reputation: 1125258
Use enumerate()
to generate an index:
def initializeNodes(heights):
ans = []
for i, height in enumerate(heights):
ans.append(Node(i, height))
return ans
You can collapse the four lines into 1 using a list comprehension:
def initializeNodes(heights):
return [Node(i, height) for i, height in enumerate(heights)]
Upvotes: 6