简体   繁体   English

如何打印此列表列表?

[英]How do I print out this list of lists?

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 Traceback: print(stocksOwned[0][count][0],'\nsakuma cena-',stocksOwned[0][count][1]) IndexError: list index out of range

I can't seem to figure why the index is out of range.我似乎无法弄清楚为什么索引超出范围。 I know indexing starts with 0. What am I not seeing or understanding here?我知道索引从 0 开始。我在这里没有看到或理解什么?

This is actually a list of lists of lists... Here's how you print:这实际上是列表列表的列表...这是您的打印方式:

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

You may mean to have:您可能意味着拥有:
stocksOwned = [['Microsoft', 150, 0.01, 0, 0], ['Tesla', 710, 0.0424, 0, 0]] (a list of lists) stocksOwned = [['Microsoft', 150, 0.01, 0, 0], ['Tesla', 710, 0.0424, 0, 0]] (列表列表)

You are calling stocksOwned[count][count] and this results to the error based on stocksOwned = [[['Microsoft', 150, 0.01, 0, 0]], [['Tesla', 710, 0.0424, 0, 0]]] .您正在调用stocksOwned[count][count] ,这会导致基于stocksOwned = [[['Microsoft', 150, 0.01, 0, 0]], [['Tesla', 710, 0.0424, 0, 0]]] Use the following code:使用以下代码:

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

Your second dimension of list has only 1 index.您的第二维列表只有 1 个索引。

stocksOwned[count][0][0]

will give you the correct value.会给你正确的价值。 Having stocksOwned[count][count][0] will make it index the next list which is not there.拥有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'

This is how it looks.这就是它的外观。 so indexing 1 in the middle one will throw error.所以在中间索引 1 会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM