首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法理解Python3枚举()

无法理解Python3枚举()
EN

Stack Overflow用户
提问于 2020-08-24 15:50:35
回答 2查看 66关注 0票数 2

问:给定一个整数数组,返回两个数字的索引,使它们相加为一个特定的目标。

您可以假设每个输入都只有一个解决方案,并且不能使用同一元素两次。

示例:

给定数字= 2,7,11,15,目标= 9,

因为nums + nums1 =2+7= 9,所以返回0,1。

代码语言:javascript
运行
复制
class Solution:
def twoSum(self, nums, target):

    lookup={}
    for cnt, num in enumerate (nums):
        if target-num in lookup:
            return lookup[target-num], cnt
        lookup[num]=cnt

我不能理解使用for循环后的步骤。我是Python新手,有人能帮我吗?

EN

回答 2

Stack Overflow用户

发布于 2020-08-24 16:10:29

让我通过解释代码的作用以及它如何解决问题来帮助您理解。

我们需要找到两个和为9的数字,为此,我们可以迭代数组中的每个数字,然后查看是否已经遇到了等于目标数字减去当前数字的数字。如果我们还没有遇到这样的数字,我们存储当前的数字及其对应的索引。

因为我们需要返回索引,所以我们希望能够查找数字-目标对并立即获得索引。该解决方案使用字典来存储数字(键),并将索引作为(值)返回。

我们遍历每个数字,如果我们以前遇到过target- number,我们可以返回当前的索引和target-number的索引,如果我们没有遇到这个数字,我们简单地存储当前的数字和它的索引。

枚举部分只提供一个索引以及被迭代数组的值,形式为(id,item)。

代码语言:javascript
运行
复制
class Solution:
    def twoSum(self, nums, target):
        # Here a dictionary is created, which will store value, index as key, value pairs.
        lookup={}
        # For every number in the array, get the index (cnt) and number (num)
        for cnt, num in enumerate (nums):
            # If we find target-num, we know that num + target-num = target
            if target-num in lookup:
                # Hence we return the index of the target-num we stored in the dict, and the index of the current value (cnt)
                return lookup[target-num], cnt
            # Otherwise we store the current number as key with its index as value
            lookup[num]=cnt
票数 1
EN

Stack Overflow用户

发布于 2020-08-24 16:31:56

enumerate()方法将计数器添加到迭代器中,并以枚举对象的形式返回它。然后可以在for循环中直接使用这个枚举对象,或者使用list()方法将其转换为元组列表。

例如

>>>list(enumerate("abc"))

给出

代码语言:javascript
运行
复制
[(0, 'a'), (1, 'b'), (2, 'c')]

为了便于理解,我对您的程序进行了注释。仔细看看,你一定会明白的。

代码语言:javascript
运行
复制
class Solution:
def twoSum(self, nums, target):
    
    # lookup is a dictionary that stores the number and its index 
    # e.g. '{7:1}'
    #     number 7 at index 1 
    lookup={}

    # As explained above cnt and num will receive values one by one along with index.
    for cnt, num in enumerate (nums):
        
        # We look if the number required to be added into the 'num' is present in dictionary
        if target-num in lookup:
            # if value found in lookup then we return the current index along with the index of number found in lookup.
            return lookup[target-num], cnt

        # After every loop insert the current value and its index into the lookup dictionary.
        lookup[num]=cnt

希望,我以你想要的方式回答了你的问题。请在下面评论,如果有什么问题没有回答,我也会尽力回答的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63556798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档