如何打印此列表?

2024-09-22 14:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

count: int = 0
while count < len(stocksOwned):
    print(stocksOwned[count][count][0],'\nsakuma cena-',stocksOwned[count][count][1])
    count += 1

stocksOwned = [[['Microsoft', 150, 0.01, 0, 0]], [['Tesla', 710, 0.0424, 0, 0]]]

Traceback: print(stocksOwned[0][count][0],'\nsakuma cena-',stocksOwned[0][count][1]) IndexError: list index out of range

我似乎不明白为什么指数超出范围。我知道索引从0开始。我在这里没有看到或理解什么


Tags: indexlencountoutmicrosoftlistintprint
3条回答

这实际上是一个列表的列表。。。以下是您打印的方式:

for stock in stocksOwned:
     print(stock[0][0],'\nsakuma cena-',stock[0][1])

您的意思可能是:
stocksOwned = [['Microsoft', 150, 0.01, 0, 0], ['Tesla', 710, 0.0424, 0, 0]](列表列表)

列表的第二个维度只有一个索引

stocksOwned[count][0][0]

将为您提供正确的值。拥有stocksOwned[count][count][0]将使它索引下一个不存在的列表

stocksOwned[0]
[['Microsoft', 150, 0.01, 0, 0]]
stocksOwned[0][0]
['Microsoft', 150, 0.01, 0, 0]
stocksOwned[0][0][0]
'Microsoft'

这就是它的样子。所以中间的索引1会抛出错误。

您正在调用stocksOwned[count][count],这将导致基于stocksOwned = [[['Microsoft', 150, 0.01, 0, 0]], [['Tesla', 710, 0.0424, 0, 0]]]的错误。 使用以下代码:

while count < len(stocksOwned):
    print(stocksOwned[count][0][0],'\nsakuma cena-',stocksOwned[count][0][1])
    count += 1

相关问题 更多 >