【问题标题】:Issue when printing dictionary打印字典时的问题
【发布时间】:2017-06-03 08:17:41
【问题描述】:

我想逐行打印以下字典,其中第二行应该是列表本身(在 Python 2x 中):

dict = {1: [10, 20, 30], 2: [40, 50]}
for i in dict:
    print ("i = %s" % i)
    for j in dict[i]:
        print dict[i][j]
    print ("\n")

这是通过关注这个answer,但仍然有这个错误说超出范围!!

i = 1
Traceback (most recent call last):
  File "./t.py", line 26, in <module>
    print dict[i][j]
IndexError: list index out of range

我正在自学 Python。如果这个问题对你们大多数人来说是微不足道的,我深表歉意。

【问题讨论】:

  • 什么是l[1][10]
  • 如果你是刚开始学习Python,最好用Python3
  • 第一个循环用于迭代键,而内部循环用于迭代在本例中为列表的值。
  • “内部迭代值”——对。并且您将该值用作索引。 l[i][j]
  • @jonrsharpe 我更改了变量,但使用了旧的错误消息。我很抱歉。我修改了帖子

标签: python index-error


【解决方案1】:

只需将dict[i][j] 更改为仅j

也不要将变量用作dict

d = {1: [10, 20, 30], 2: [40, 50]}
for i in d:
    print ("i = %s" % i)
    for j in d[i]:
        print j
    print ("\n")

输出:

C:\Users\dinesh_pundkar\Desktop>python dsp.py
i = 1
10
20
30


i = 2
40
50



C:\Users\dinesh_pundkar\Desktop>

【讨论】:

  • 哦!非常感谢...事实上,我想打印整个列表而不是列表值
【解决方案2】:

您将列表值用作列表的索引。 相反,只需打印值:

dict = {1: [10, 20, 30], 2: [40, 50]}
for i in dict:
    print ("i = %s" % i)
    for j in dict[i]:
        print j
    print ("\n")

【讨论】:

    【解决方案3】:

    列表只是键返回的值...

    首先,不要“隐藏”保留字(例如,使用“dict”作为变量名。)

    其次,您希望打印的列表只是为提供的键返回的值。您的示例代码正在遍历列表,然后将结果值用作索引,但事实并非如此。

    以下代码与您的示例最接近,可以执行您所描述的您希望它执行的操作:

    d = {1: [10, 20, 30], 2: [40, 50]}  
    for i in d:  
      print ("i = %s" % i)  
      print d[i]  
    

    在交互式 Python 会话中产生以下结果:

    >>> d = {1: [10, 20, 30], 2: [40, 50]}  
    >>> for i in d:  
    ...   print ("i = %s" % i)  
    ...   print d[i]  
    ... 
    i = 1
    [10, 20, 30]
    i = 2
    [40, 50]  
    >>>  
    

    更严格的实现可能如下所示:

    d = {1: [10, 20, 30], 2: [40, 50]}  
    for k,v in d.items():  
      print ("i = %s\n%s" % (k,v))  
    

    这再次在交互式 Python 会话中产生以下结果:

    >>> d = {1: [10, 20, 30], 2: [40, 50]}  
    >>> for k,v in d.items():  
    ...   print ("i = %s\n%s" % (k,v))  
    ... 
    i = 1
    [10, 20, 30]
    i = 2
    [40, 50]
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2017-12-12
      相关资源
      最近更新 更多