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



所以我正在创建一个函数,它的行为方式与内置枚举函数类似,但返回元组列表(索引,值(。

这是我的函数:

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.index(i) .如果存在多个同一对象,则 index 函数返回第一个索引。由于你有 3 'x',它将始终返回第一个'x'的索引。

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

最新更新