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

时间:2016-04-24 21:37:46

标签: python python-2.7 list-comprehension

我使用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]

3 个答案:

答案 0 :(得分:0)

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

>>> 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]]

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

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