简体   繁体   English

将对象元组转换为字符串元组

[英]Convert a tuple of objects to a tuple of strings

>>> import MySQLdb
>>> db = MySQLdb.connect( host = "localhost", user ="root", passwd = "", db = "smoky_db" )
>>> cur = db.cursor()
>>> cur.execute( 'SELECT * FROM logs' )
3L
>>> rows = cur.fetchall()
>>> rows
((1L, datetime.datetime(2014, 5, 21, 0, 0)), (1L, datetime.datetime(2014, 5, 22, 0, 0)) )

how can I convert the returned tuples of objects to tuples of strings, Something like this: 我如何将返回的对象元组转换为字符串元组,就像这样:

(('1', '2014-05-21 00:00:00'), ('2', '2014-05-22 00:00:00'))

Simply iterate the items and convert them to tuples, like this 只需迭代项目并将其转换为元组,就像这样

print tuple(tuple(str(item) for item in items) for items in d)
# (('1', '2014-05-21 00:00:00'), ('1', '2014-05-22 00:00:00'))

Here we have used two generator expressions. 在这里,我们使用了两个生成器表达式。 The innermost one ( str(item) for item in items ) will be executed for every item in the original tuple. 将对原始元组中的每个项目执行最里面的一个( str(item) for item in items And when the nested items are stringified, we iterate the generator expression and convert that to a tuple again. 当嵌套的项目被字符串化时,我们迭代生成器表达式并将其再次转换为元组。

Call str on every element: 在每个元素上调用str

>>> [tuple(map(str, tup)) for tup in tups]
[('1', '2014-05-21 00:00:00'), ('1', '2014-05-22 00:00:00')]

This works because datetime objects implement __str__ method, being called by str function. 之所以__str__ ,是因为datetime对象实现了str函数调用的__str__方法。 From the documentation : 文档中

For a date d, str(d) is equivalent to d.isoformat(' '). 对于日期d,str(d)等效于d.isoformat('')。

这应该可以解决问题:

out = tuple((str(k),str(v)) for (k,v) in rows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM