【问题标题】:How to make code that's functionally similar to enumerate without actually using enumerate?如何在不实际使用枚举的情况下制作功能类似于枚举的代码?
【发布时间】:2017-02-18 08:58:21
【问题描述】:

我想编写一个代码,打印出在给定列表中出现两次的数字的值,但它们不允许我们在 python 上使用内置函数。如果不使用枚举,我将如何编写它?

def find_second_occurrence(xs,v):
    count = 0
    value = None
    for i, x in enumerate(xs):
        if v == x:
            count += 1
            if count == 2:
                return i
    if (count < 2):
        return value

【问题讨论】:

  • 实现自己的enumerate函数并使用它。
  • @RickTeachey 我不知道从哪里开始。我不太了解枚举的概念
  • 你会做一个和你做的一样的函数。每次循环时,计数器都会增加。它返回一个包含项目编号和项目的二元组列表。
  • 请注意,您返回的不是重复数字的,而是它的第二个index

标签: python list function python-3.x enumerate


【解决方案1】:

你自己的枚举函数可能是这样的:

def my_enumerate(a_list):
    result = []
    counter = 0
    for item in a_list:
        result.append((counter, item))
        counter += 1
    return result

与内置的enumerate 不同,它是一次生成一个项目的生成器,您的函数返回一个列表。

【讨论】:

    【解决方案2】:

    enumerate(sequence) 非常类似于以下形式的构造:

    for i in range(len(sequence)):
        # get sequence[i] and return i and sequence[i] for all i's
    

    因此,在您的代码中,完全替换 enumerate 可以通过以下方式完成:

    for i in range(len(xs)):
        x = xs[i]             
        if v == x:
            count += 1
            if count == 2:
                return i
    

    或者,不指定 x 名称来临时保存序列项:

    for i in range(len(xs)):           
        if v == xs[i]:
            count += 1
            if count == 2:
                return i
    

    创建一个小my_enumerate 函数,也很简单:

    def my_enumerate(sequence, start=0):
        for i in range(len(sequence)):
            yield start+i, sequence[i]
    

    start 也被定义为与enumerate 中使用的匹配,并获得默认值0

    您可以创建一个列表(生成器推导类似于yielding)推导而不是yielding 值(如果这让您感到困惑)并返回它:

    def my_enumerate(sequence, start=0):
        return [(start+i, sequence[i]) for i in range(len(sequence))]
    

    【讨论】:

    • 你能解释一下 xs[i] 的作用吗?
    • @fip xs 是您的列表,例如 xs = [5, 1, 2, 4]xs[i]索引该列表并获取位于i 位置的项目。因此,例如,xs[0] 将是 5xs[1] 将是 1xs[2]2 等等。请参阅here 了解有关列表的 Python 教程,其中对此进行了解释:)
    • 有道理!谢谢!
    【解决方案3】:

    也可以参考Pythonsdocumentation,这里建议如下:

    def enumerate(sequence, start=0):
        n = start
        for elem in sequence:
            yield n, elem
            n += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2015-12-24
      • 2020-02-25
      • 1970-01-01
      相关资源
      最近更新 更多