繁体   English   中英

Python列表理解使列表变得扁平化

[英]Python list comprehension is flattening out the lists

我使用pyodbc从SQL服务器提取数据,并希望在插入另一个数据库(表)之前将datetime.datetime列值转换为epoch。 当我这样做时,我看到我的列表清单变得扁平了。 如何避免这个请。

   >>> scur.execute("select top 2 * from database.dbo.table")
<pyodbc.Cursor object at 0x1f2d930>
>>> cnt = scur.fetchall()
>>> rowlist = [list(l) for l in cnt]

>>> rowlist

[[404458, 348, datetime.datetime(2015, 10, 9, 14, 13), datetime.datetime(2015, 10, 9, 0, 0), u'ded1598f-eed1-4edb-bfe4-f866592e9a51', u'el ong', u'', 1, 0, 0.091499999999999998, 0.0, -999999.0, -999999.0, 0.0, 0.25, -999999.0, -999999.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, None, None, 1127, None, u'150610007', u'10', u'CMMQ0056', None, u'0', None, None, None, None, None, False, None, None], [404459, 349, datetime.datetime(2015, 10, 9, 14, 13), datetime.datetime(2015, 10, 9, 0, 0), u'174b2d32-e71d-40b0-9c1d-cab7274c9b40', u'el ong', u'', 1, 0, 0.055399999999999998, 0.0, -999999.0, -999999.0, 0.0, 0.40000000000000002, -999999.0, -999999.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, None, None, 1127, None, u'150610007', u'10', u'CMMQ0056', None, u'0', None, None, None, None, None, False, None, None]]

>>> [row[i].strftime('%s') if isinstance(row[i], datetime.date) else row[i] for row in rowlist for i in range(len(row))]

[404458, 348, '1444414380', '1444363200', u'ded1598f-eed1-4edb-bfe4-f866592e9a51', u'el ong', u'', 1, 0, 0.091499999999999998, 0.0, -999999.0, -999999.0, 0.0, 0.25, -999999.0, -999999.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, None, None, 1127, None, u'150610007', u'10', u'CMMQ0056', None, u'0', None, None, None, None, None, False, None, None, 404459, 349, '1444414380', '1444363200', u'174b2d32-e71d-40b0-9c1d-cab7274c9b40', u'el ong', u'', 1, 0, 0.055399999999999998, 0.0, -999999.0, -999999.0, 0.0, 0.40000000000000002, -999999.0, -999999.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, None, None, 1127, None, u'150610007', u'10', u'CMMQ0056', None, u'0', None, None, None, None, None, False, None, None]

假设你有一个列表列表(一个更简单的例子):

>>> LoL=[[datetime.datetime(2015, 10, 9, 14, 13),'a','b', 1,2], [datetime.datetime(2016, 11, 9, 14, 13),'c','d', 3,4]]

然后,您可以使用嵌套列表解析来保留嵌套列表:

>>> [[e.strftime('%s') if isinstance(e, datetime.date) else e for e in rowlist] for rowlist in LoL]
[['1444425180', 'a', 'b', 1, 2], ['1478729580', 'c', 'd', 3, 4]]

这应该做到这一点。 这将在执行转换时保留所需的列表结构:

[[v.strftime('%s') if isinstance(v, datetime.date) else v for v in row] for row in rowlist]

您需要使用内部列表comp进行迭代以便保留行,您还可以简单地遍历每行中的元素而不需要范围。

[int(ele.strftime("%s"))  if isinstance(ele, datetime.datetime) else ele for ele in sub] for sub in l]

暂无
暂无

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

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