【问题标题】:I have a problem with the for loop Python我对 for 循环 Python 有疑问
【发布时间】:2022-12-13 01:57:35
【问题描述】:

我在使用 for 循环时遇到问题,我不知道为什么我的循环没有按预期工作。

代码:

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] != target:
                pos = pos + 1
                
            print(pos)
            break

Solution.searchInsert([1,3,5,6], 5)

该程序接收一个整数数组和另一个我称为目标的整数,脚本必须返回数组中目标编号所在的位置。

在这种情况下,我的数组“nums”包含 [1,3,5,6],我的目标是 5,所以结果必须是 2,因为目标 (5) 的编号在数组的位置“2” .

当我运行脚本时,问题就来了。而不是 2 脚本给了我 1

如果有人发现代码中的错误,请告诉我。

【问题讨论】:

  • 为什么不直接使用nums.index(target)
  • 您在循环外实例化迭代器并在控制结构外递增它。这很好奇。声明 for 循环后,尝试使用此语句跟踪您的值: print("i is %i, pos is %i, target is %i" %(i,pos, target))
  • 你似乎在第一次迭代后打破了循环(但你帖子中的缩进很奇怪)。这就是为什么你得到 1,这是 pos 的第一次更新。
  • 您的函数将始终隐式返回 None 因为您明确休息为了在第一次迭代期间循环。您可能还想重新阅读此功能的 Leetcode 说明

标签: python arrays for-loop insert target


【解决方案1】:

您在第一次迭代后关闭循环:您需要添加一个 else: 块以便它可以继续进行直到满足条件...

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] != target:
                pos = pos + 1
            else:    
                print(pos)
                break
>>> Solution.searchInsert([1,3,5,6],5)
2

【讨论】:

  • 有道理,我不知道我怎么没有意识到这一点。谢谢你的帮助
【解决方案2】:

我在这里发布的只是固定代码,但正如其他人指出的那样,这是一种奇怪的处理方式。但我明白,如果你学习 Python 并且来自其他语言(Visual Basic?),那么你会走这条路。 在 python 中缩进是至关重要的。在您的代码中,您需要在每次代码经过循环时增加 pos,而不仅仅是当您找到/没有找到您想要的值时。

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] == target:
                print(pos) #replace with return pos ?
                break
            pos = pos + 1 #increase outside above condition

Solution.searchInsert([1,3,5,6], 5)

为了使此代码更容易,一个班轮,调查其他用户 cmets。或者研究数组索引、长度和后来的 pandas 模块。

【讨论】:

  • 不要忘记给答案投票或标记为已回答。
  • 我不能投票,因为我需要 15 个声望:(
  • 我不能将多个答案标记为已接受,这就是为什么我评论你说你的答案也有效并且效果很好
【解决方案3】:

你可以使用 enumerate 给你索引和值

class Solution:
    def searchInsert(nums, target):
        for index, value in enumerate(nums):
            if value == target:
                return index 
             
print(Solution.searchInsert([1,3,5,6], 5))

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2019-10-17
    相关资源
    最近更新 更多