内置的 map() 函数如何影响 itemgetter() 和数据库游标? - Python

How does the built-in map() function affect itemgetter() and database cursors? - Python

在 Python 2.7 中,使用 MySQLdb 包,我无法理解 itemgetter() 和数据库游标的 execute() 函数的以下行为:

c = db.cursor()
c.execute('SELECT 1+2')  # could be any other valid query
map(itemgetter(0), c)

这将 return 一个列表 [3]

但是 itemgetter(0)(c)c[0] 给出了一个 TypeError 说 'Cursor' 对象不支持索引,这是完全可以理解的。

map()itemgetter() 如何从 数据库游标 before 游标调用 fetchonefetchall 方法?

根据the description of map

Apply function to every item of iterable and return a list of the results.

根据the description of iterable

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...).

因此,可迭代对象必须定义 __iter__()__getitem__()

the source of MySQLdb 开始,游标对象定义 __iter__() 而不是 __getitem__()

def __iter__(self):
    return iter(self.fetchone, None)

因为它没有定义 __getitem__(),所以 itemgetter(0)(c)c[0] 都不起作用。 但是,由于它定义了 __iter__(),您可以使用 map() item 来获取作为 self.fetchone.

结果的每个项目

因此 itemgetter(0) 实际上应用于行对象 self.fetchone() 的结果。 行对象似乎只是一个列表对象,所以你可以应用 itemgetter(0)(row) which returns row[0]