由於sqlite3 select語句的結果,我得到了一組元組的迭代,我想給這個迭代器賦予一個需要字符串迭代的函數。我如何覆蓋下一個函數來給出元組的第一個索引?或者更準確地說,做這件事的正確方法是什麼?Python:將可迭代的元組轉換爲可迭代的字符串
>>> res = conn.execute(query,(font,))
>>> train_counts = count_vect.fit_transform(res)
AttributeError: 'tuple' object has no attribute 'lower'
編輯:
因爲映射涉及循環訪問它需要兩倍多的時間,只是構建一個發電機作爲尼克拉斯所提供的完整列表。
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
@NiklasB。請將您的評論發佈爲答案,我將接受它 – zenpoy
爲了公平起見:Python 3中的map和發生器表達式一樣懶惰 –