Python: converting a tuple repeated to a string repeated

I get iterable tuples as a result of the sqlite3 select statement, and I want to give this iterable function that expects the row to be iterable. How can I override the following function to give the first tuple index? Or, to be more precise, what is the correct pythonic way to do this?

>>> res = conn.execute(query,(font,))
>>> train_counts = count_vect.fit_transform(res)

AttributeError: 'tuple' object has no attribute 'lower'

EDIT:

Since mapping involves iterating over the entire list, it takes twice as much time as just creating a generator at the suggestion of 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
+3
source share
2 answers

A simple solution would be to use a generator expression:

count_vect.fit_transform(t[0] for t in res)
+2
source

, ; 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]
+4

All Articles