gpt4 book ai didi

Python:将可迭代的元组转换为可迭代的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 13:50:15 25 4
gpt4 key购买 nike

作为 sqlite3 select 语句的结果,我得到了元组的可迭代对象,我想将此可迭代对象提供给需要可迭代字符串的函数。如何重写 next 函数以给出元组的第一个索引?或者更准确地说,这样做的正确 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

最佳答案

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

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

实际上在那种情况下你可以完全避免 lambda 并使用列表理解:

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

关于Python:将可迭代的元组转换为可迭代的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10563707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com