Python 中 TypeError: ‘map’ object is not subscriptable 错误

当我们尝试访问特定索引处的地图对象时,会出现 Python“TypeError: ‘map’ object is not subscriptable”。 要解决该错误,请先将地图对象转换为列表,然后再通过索引访问它,例如 new_list = list(map(int, a_list))

下面是一个产生上述错误的示例

a_list = ['2', '4', '6', '8']


new_list = map(int, a_list)
print(new_list)  # 👉️ <map object at 0x7fde832679a0>

# ⛔️ TypeError: 'map' object is not subscriptable
print(new_list[0])

在 Python 3 中,map() 函数返回一个地图对象,而不是一个列表。

要解决该错误,请使用 list() 函数将 map 对象转换为列表。

a_list = ['2', '4', '6', '8']

new_list = list(map(int, a_list))
print(new_list)  # 👉️ [2, 4, 6, 8]

print(new_list[0])  # 👉️ 2

map() 函数将一个函数和一个可迭代对象作为参数,并使用可迭代对象的每个项目调用该函数。

该函数返回一个地图对象,地图对象不可订阅(无法通过索引访问)。

如果需要访问,可以使用方括号:

  • 特定索引处的列表
  • 特定索引处的元组
  • 特定索引处的字符串
  • 字典中的特定键

解决错误的另一种方法是使用 for 循环迭代 map 对象,而不必将其转换为列表。

a_list = ['2', '4', '6', '8']

new_list = []

map_obj = map(int, a_list)

for item in map_obj:
    print(int(item))

    new_list.append(int(item))

print(new_list) # 👉️ [2, 4, 6, 8]

print(new_list[0])  # 👉️ 2

print(new_list[:2])  # 👉️ [2, 4]

Map 对象是惰性求值的,所以我们使用 for 循环来遍历对象。

我们可以选择将使用每个项目调用函数的结果追加到列表中。

比必须将地图对象转换为列表更好的方法是使用列表推导。

a_list = ['2', '4', '6', '8']

new_list = [int(item) for item in a_list]

print(new_list)  # 👉️ [2, 4, 6, 8]

我们使用列表理解来迭代原始列表。

列表推导用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们用当前项目调用 int() 函数并返回结果。

列表推导返回一个包含结果的新列表。

列表推导式可以用作 map 函数的替代品。 我们所要做的就是对每个列表项调用一个函数并返回结果。

我们还可以将列表理解或映射函数与用户定义的函数一起使用。

def do_math(a):
    return a + 100


a_list = [2, 4, 6, 8]

result = list(map(do_math, a_list))
print(result)  # 👉️ [102, 104, 106, 108]
print(result[0])  # 👉️ 102

result = [do_math(item) for item in a_list]
print(result)  # 👉️ [102, 104, 106, 108]
print(result[0])  # 👉️ 102

object is not subscriptable”TypeError 基本上意味着无法使用方括号访问对象。

我们应该只使用方括号来访问可订阅对象。

Python 中的可订阅对象是:

  • list
  • tuple
  • dictionary
  • string

必须使用 list()tuple()dict() 或 str() 类将所有其他对象转换为可订阅对象,以便能够使用括号表示法。

可订阅对象实现了 __getitem__ 方法,而非可订阅对象则没有。

a_list = [1, 2, 3]

# 👇️ <built-in method __getitem__ of list object at 0x7f71f3252640>
print(a_list.__getitem__)

总结

当我们尝试访问特定索引处的 map 对象时,会出现 Python“TypeError: ‘map’ object is not subscriptable”。 要解决该错误,请先将 map 对象转换为列表,然后再通过索引访问它,例如 new_list = list(map(int, a_list))