Python:将元组iterab转换为字符串iterab

2024-05-29 03:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我从sqlite3select语句得到了一个元组的iterable,我想把这个iterable赋给一个需要字符串iterable的函数。如何重写下一个函数以给出元组的第一个索引?或者更准确地说,什么是Python式的正确方法?在

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

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

编辑:

由于映射涉及到遍历整个列表,因此构建生成器所需的时间是Niklas提供的时间的两倍。在

^{pr2}$

Tags: 方法函数字符串execute时间trainres语句
2条回答

您需要编写一个将每个元组转换为字符串的函数;然后可以使用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)

如果需要每个元组中的第一项,则函数可以是:

^{pr2}$

(假设第一个元素已经是字符串)。在

实际上,在这种情况下,您可以完全避免lambda,使用列表理解:

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

简单的解决方案是使用生成器表达式:

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

相关问题 更多 >

    热门问题