【问题标题】:I don't know how to print in this case number 5. I also tried return在这种情况下,我不知道如何打印 5。我也尝试过 return
【发布时间】:2021-08-16 03:21:19
【问题描述】:

我想提取5:

my_list = [[123],[456],[789]]
print(my_list[1][1])

错误信息:

Traceback (most recent call last):
  File "C:\Users\IK\PycharmProjects\WithoutUSB\Udemy course 1\more than 1 dimension.py", line 4, in <module>
    f()
  File "C:\Users\IK\PycharmProjects\WithoutUSB\Udemy course 1\more than 1 dimension.py", line 3, in f
    return(my_list[1][1])
IndexError: list index out of range

【问题讨论】:

    标签: python list indexing console numbers


    【解决方案1】:

    不能直接访问整数中的位置,需要先转换成字符串:

    my_list = [[123],[456],[789]]
    print(str(my_list[1][0])[1])
    

    输出:5

    细分:

    >>> my_list[1]
    [456]
    >>> my_list[1][0]
    456
    >>> str(my_list[1][0])
    '456'
    >>> str(my_list[1][0])
    '5'
    

    【讨论】:

    • 您可以添加一个int 以将5 最后转换回一个整数。
    【解决方案2】:

    你也这样定义

    my_list = [[1,2,3],[4,5,6],[7,8,9]]
    print(my_list[1][1])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2018-10-29
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多