Python列表迭代

Python列表迭代,python,list,iteration,Python,List,Iteration,所以我有一个高度列表: heights = [1, 2, 3, 5, 7, 8, 8, 13] 我使用这个函数将每个高度整数值及其索引存储在一个名为Node的类的列表中 def initializeNodes(heights): ans = [] for height in heights: ans.append(Node(heights.index(height), height)) return ans 但我的问题是,因为它们在列表中是两个8,所以

所以我有一个高度列表:

heights = [1, 2, 3, 5, 7, 8, 8, 13]
我使用这个函数将每个高度整数值及其索引存储在一个名为Node的类的列表中

def initializeNodes(heights):
    ans = []
    for height in heights:
        ans.append(Node(heights.index(height), height))
    return ans
但我的问题是,因为它们在列表中是两个8,所以它们在列表中的前8位都是5:

0 1
1 2
2 3
3 5
4 7
5 8
5 8
7 13
我怎么能绕过这个? 谢谢

用于生成索引:

def initializeNodes(heights):
    ans = []
    for i, height in enumerate(heights):
        ans.append(Node(i, height))
    return ans
您可以使用列表将四行折叠为1:

def initializeNodes(heights):
    return [Node(i, height) for i, height in enumerate(heights)]

list.index
的问题在于它只返回该项第一次出现的索引

>>> heights = [1, 2, 2, 3, 5, 5, 7, 8, 8, 13]
>>> heights.index(2)
1
>>> heights.index(5)
4
>>> heights.index(8)
7
有关列表索引的帮助信息:

L.index(value、[start、[stop]])->integer——返回 价值观

您可以向
列表提供不同的
开始
值。索引
大于0,以获取重复项目的索引:

>>> heights.index(5,heights.index(5)+1) #returns the index of second 5
5

但是这非常麻烦,@MartijnPieters已经提到的一个更好的解决方案是
enumerate

问题是您正在从值生成索引,为什么不反过来呢

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

这将创建一个从0到高度长度的列表,然后将附加索引,然后是此索引处的高度。

这非常完美,令人惊讶地比我想象的简单得多!lol已经有一段时间没有使用python了,并且忘记了如何使用枚举,愚蠢的方法@Martijn Pieters建议的枚举方法更好。