gpt4 book ai didi

Python 列表迭代

转载 作者:行者123 更新时间:2023-11-28 20:48:03 25 4
gpt4 key购买 nike

所以我有一个高度列表:

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,所以它给了它们列表中 5 的前 8 个相同位置:

0 1
1 2
2 3
3 5
4 7
5 8
5 8
7 13

我该如何解决这个问题?谢谢!

最佳答案

使用enumerate()生成索引:

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

您可以使用列表推导式将四行合并为一行:

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

关于Python 列表迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17573949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com