【问题标题】:looping over a list/arry: for item in list vs for item in range (0, len(list)) both showing different output遍历列表/数组:for item in list vs for item in range (0, len(list)) 两者都显示不同的输出
【发布时间】:2023-01-19 14:38:53
【问题描述】:

代码:1

class Solution:
    def firstElementKTime(self,  a, n, k):
        # code here
        countDict = {}
        for i in a:
            if (a[i] in countDict):
                countDict[a[i]] = countDict[a[i]] + 1
            else:
                countDict[a[i]] = 1
        for i in a:
            if countDict[a[i]] == k:
                return a[i]
        return -1

代码1的错误: 追溯(最近一次通话): 文件“/home/91ded90adaf6c5d579e2dbec3cedff79.py”,第 40 行,位于 主要的() 文件“/home/91ded90adaf6c5d579e2dbec3cedff79.py”,第 34 行,在 main 打印(ob.firstElementKTime(a,n,k)) 文件“/home/91ded90adaf6c5d579e2dbec3cedff79.py”,第 9 行,在 firstElementKTime 中 如果(countDict 中的 a[i]): IndexError:列表索引超出范围

代码:2

        countDict = {}
        for i in range(0, len(a)):
            if a[i] in countDict:
                countDict[a[i]] = countDict[a[i]] + 1
            else:
                countDict[a[i]] = 1
            i = i + 1
        for i in a:
            if countDict[a[i]] == k:
                return a[i]
        return -1

没有错误:

我希望上述代码中的行为相同..

【问题讨论】:

    标签: python python-3.x list for-loop


    【解决方案1】:

    第一个在 a 的元素上运行,而不是在索引上运行。 所以 a[i] 就像第一次迭代中的 a[a[0]] 。

    因为我在

    会给你一个[0],一个[1],...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2022-12-26
      • 2013-08-25
      • 2016-12-16
      • 1970-01-01
      相关资源
      最近更新 更多