【问题标题】:Why do I get index error I try to multiply an element of a list?为什么我尝试将列表的元素相乘时出现索引错误?
【发布时间】:2021-05-24 00:20:47
【问题描述】:

我是 Python 新手,不太了解列表与数组有何不同。在搜索时,它们被定义为动态数组。我无法理解为什么当我尝试将列表中的元素相乘时得到 IndexError,如下面的倒数第三行代码所示。如果我尝试像数组一样操作列表,我会面临哪些限制?在这里,我分享了我的部分代码。 在此先感谢:)

import cs50

def main():
    credit = cs50.get_string("Number: ")
    while(int(credit) < 0):
        credit = cs50.get_string("Number: ")
    if int(credit) < 1000000000000 or int(credit) > 9999999999999999:
        print("INVALID")
        quit()


    cred = credit.split()
    n = len(credit)
    cred.pop()
    cred.reverse()

    i = 0
    
    while i < n:
        
        cred[i] = (int(cred[i]) % 10) + (int(cred[i]) // 10)
        i += 2
main()

【问题讨论】:

    标签: python arrays list cs50


    【解决方案1】:
    cred.pop()
    

    如果列表只包含一个元素,它将使列表为空列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多