Trying to write function map() getting error IndexError: list index out of range

Trying to write function map() getting error IndexError: list index out of range

我正在尝试编写函数 map() 时出现错误 IndexError:列表索引超出范围

     def map1(fn, a):
         i = 0
         b = []
         while i != len(a):
             print(len(a))
             i += 1
             b.append(fn(a[i]))
         return b

具有工作功能

    def translate(x):
        dicti = {"merry": "god", "christmas": "jul", "and": "och", "happy": "gott", "new": "nytt", "year": "år"}
        return dicti[x]

收到错误

     IndexError: list index out of range

您在访问 a 之前递增 i。在最后一次迭代中,i 在循环体的开头是 len(a)-1,然后递增到 len(a),但这刚好在有效索引范围之外。要修复它,您必须在访问后增加:

while i != len(a):
    b.append(fn(a[i]))
    i += 1

但是,一种改进的方法是使用 range,它会自动为您生成 i 的正确值:

for i in range(len(a)):
    b.append(fn(a[i]))

更好的方法是直接遍历 a 的条目:

for x in a:
    b.append(fn(x))

更好的方法是使用列表理解:

b = [fn(x) for x in a]

您在使用前增加i

def map1(fn, a):
         i = 0
         b = []
         while i != len(a):
             print(len(a))

             b.append(fn(a[i]))
             i += 1
         return b

def translate(x):
        dicti = {"merry": "god", "christmas": "jul", "and": "och", "happy": "gott", "new": "nytt", "year": "ar"}
        return dicti[x]

map1(translate, ["merry", "and"])