2012-05-12 70 views
3

由於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 
+0

@NiklasB。請將您的評論發佈爲答案,我將接受它 – zenpoy

+0

爲了公平起見:Python 3中的map和發生器表達式一樣懶惰 –

回答

2

簡單的解決辦法是用生成器表達式:

count_vect.fit_transform(t[0] for t in res) 
4

你需要編寫,將每個元組轉換爲字符串的函數;那麼您可以使用map將元組的序列轉換爲一系列字符串。

例如:

# assume each tuple contains 3 integers 
res = ((1,2,3), (4,5,6)) 

# converts a 3-integer tuple (x, y, z) to a string with the format "x-y-z" 
convert_to_string = lambda t: "%d-%d-%d" % t 

# convert each tuple to a string 
strings = map(convert_to_string, res) 

# call the same function as before, but with a sequence of strings 
train_counts = count_vect.fit_transform(strings) 

如果你想從每個元組的第一個項目,你的函數可以是:

convert_to_string = lambda t: t[0] 

(假設第一個元素已經是一個字符串)。

其實在這種情況下,你可以完全避免的拉姆達並用一個列表理解:

strings = [t[0] for t in res] 
+2

您可以使用列表理解來初始化map/lambda也有點:'strings = [「%d-%d-%d」%(x,y,z)for x,y,z in res]' – 2012-05-12 12:36:55