【问题标题】:How to Fix "List Index out of range" in python? [duplicate]如何修复python中的“列表索引超出范围”? [复制]
【发布时间】:2020-05-19 07:22:39
【问题描述】:
#function description   
 def getMoneySpent(keyboards, drives, b):
        q = []
        for i in range(len(keyboards)):
            for j in range(len(drives)):
                q.append(keyboards[i] + drives[j]) 
        for m in range(len(q)):
            if(q[m] > b):
                q.remove(q[m])
            else:
                pass
        if q is not None:
            return max(q)
        else:
            return -1

错误信息是:

Traceback (most recent call last):
    File "Solution.py", line 42, in <module>
        moneySpent = getMoneySpent(keyboards, drives, b)
    File "Solution.py", line 15, in getMoneySpent
        if(q[m] > b):
    IndexError: list index out of range

不断收到此错误消息。这是hackerrank中的一个问题,我将在下面链接给任何想要进一步参考的人:

https://www.hackerrank.com/challenges/electronics-shop/problem

【问题讨论】:

标签: python list iteration


【解决方案1】:

问题是q.remove(q[m]),您在迭代列表时正在从列表中删除项目。

一种解决方案是将所有需要的ms 保存到另一个列表中,然后在循环完成后将其删除。

您可以查看这些链接以获得更好的线索:

How to delete list items while iterating

Another link

你可以这样理解:

q[:] = [i for i in q if i <= b]

将这一行而不是你的 for 循环放在 q 上。

还要注意:

else:
    pass

是多余的,可以去掉。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    def getMoneySpent(keyboards, drives, b):
        q = []
        for k in keyboards :
            for d in drives :
                price = k + d
                if price <= b :
                    q.append(price) 
    
        return max(q) if q else -1
    

    与其删除元素,不如一开始就不要添加它们......

    【讨论】:

    • 这是准确的。
    猜你喜欢
    • 2019-09-15
    • 1970-01-01
    • 2019-10-13
    • 2019-06-24
    • 2013-06-16
    • 2019-10-01
    • 1970-01-01
    • 2019-10-02
    相关资源
    最近更新 更多