作为 sqlite3 select 语句的结果,我得到了一个可迭代的元组,我想将此可迭代对象提供给一个期望字符串可迭代对象的函数。如何覆盖下一个函数以给出元组的第一个索引?或者更准确地说,这样做的正确pythonic方式是什么?
>>> res = conn.execute(query,(font,))
>>> train_counts = count_vect.fit_transform(res)
AttributeError: 'tuple' object has no attribute 'lower'
编辑:
由于映射涉及迭代整个列表,因此它所花费的时间是 Niklas 提供的构建生成器的两倍。
first = """
l = list()
for i in xrange(10):
l.append((i,))
for j in (i[0] for i in l):
j
"""
second = """
l = list()
for i in xrange(10):
l.append((i,))
convert_to_string = lambda t: "%d" % t
strings = map(convert_to_string, l)
for j in strings:
j
"""
third = """
l = list()
for i in xrange(10):
l.append((i,))
strings = [t[0] for t in l]
for j in strings:
j
"""
print "Niklas B. %f" % timeit.Timer(first).timeit()
print "Richard Fearn %f" % timeit.Timer(second).timeit()
print "Richard Fearn #2 %f" % timeit.Timer(third).timeit()
>>>
Niklas B. 4.744230
Richard Fearn 12.016272
Richard Fearn #2 12.041094