Python 类似枚举的映射列表模式

Python 类似枚举的映射列表模式,python,Python,因此,我创建了一个函数,它的行为与内置枚举函数类似,但返回元组列表index,value 这是我的职责: def my_enumerate(items): """return a list of tuples (i, item) where item is the ith item, with 0 origin, of the list items""" result = [] for i in items: tuples = ((items.i

因此,我创建了一个函数,它的行为与内置枚举函数类似,但返回元组列表index,value

这是我的职责:

def my_enumerate(items):
    """return a list of tuples (i, item) where item is the ith item, 
    with 0 origin, of the list items"""
    result = []
    for i in items:
        tuples = ((items.index(i)), i)
        result.append(tuples)
    return result
因此,在进行以下测试时:

ans = my_enumerate([10, 20, 30])
print(ans)
它将返回:

[(0, 10), (1, 20), (2, 30)]
因此,它确实有效,但在使用以下各项进行测试时:

ans = my_enumerate(['x', 'x', 'x'])
print(ans)
它返回:

[(0, 'x'), (0, 'x'), (0, 'x')]
应在哪里:

[(0, 'x'), (1, 'x'), (2, 'x')]
我如何获取它,使其返回此值?

问题是items.indexi。如果同一对象有多个索引,index函数将返回第一个索引。由于您有3个“x”,它将始终返回第一个“x”的索引


对不起,您的预期输出与enumerate本身有何不同?它用于学校实验室,我们不打算在那里使用enumerate函数。请不要将答案用作注释。如果你有问题,把它们留在对问题的评论中。不,这是一个答案。这可能会起作用,但问题是。这是学校练习的一部分,其中函数不应调用内置枚举函数。
def my_enumerate(items):
    """
    return a list of tuples (i, item) where item is the ith item, with 0 origin, of the list items
    """

    result = []
    for index in range(len(items)):
        tuples = (index, items[index])
        result.append(tuples)

    return result