如何将包含多个列表的列表分成一个列表?

时间:2015-03-25 13:16:50

标签: python list

我在Python编码。

我能够编写返回我想要的日期列表的代码。现在,对于每个日期,我想找到该日期的单元格值。为了做到这一点,我写了一个for循环:

element = []
for item in result:
    cell_list = worksheet2.findall(item)
    element.append(cell_list)

当我打印元素时,代码返回以下响应:

[[<Cell R6C3 '2/18/2015'>, <Cell R11C3 '2/18/2015'>], [<Cell R16C3 
'2/19/2015'>, <Cell R21C3 '2/19/2015'>, <Cell R26C3 '2/19/2015'>, <Cell R31C3 
'2/19/2015'>, <Cell R36C3 '2/19/2015'>, <Cell R41C3 '2/19/2015'>], [<Cell 
R46C3 '3/10/2015'>, <Cell R51C3 '3/10/2015'>, <Cell R56C3 '3/10/2015'>], 
[<Cell R61C3 '3/17/2015'>, <Cell R66C3 '3/17/2015'>, <Cell R71C3 '3/17/2015'>, 
<Cell R76C3 '3/17/2015'>, <Cell R81C3 '3/17/2015'>, <Cell R86C3 '3/17/2015'>, 
<Cell R91C3 '3/17/2015'>, <Cell R96C3 '3/17/2015'>], [<Cell R101C3 
'3/18/2015'>, <Cell R106C3 '3/18/2015'>, <Cell R111C3 '3/18/2015'>, <Cell 
R116C3 '3/18/2015'>, <Cell R121C3 '3/18/2015'>, <Cell R126C3 '3/18/2015'>, 
<Cell R131C3 '3/18/2015'>]]

如何让代码不将多个列表放入一个列表?我只想要一个包含所有这些单元格的大列表,而不是一个列表中的多个列表。

3 个答案:

答案 0 :(得分:1)

快速回复

element.extend(cell_list)

答案 1 :(得分:0)

list.extend()有效,但另一种可能性是+=运算符:

element += cell_list

答案 2 :(得分:0)

您可以使用chain功能来链接您的列表。它返回迭代器,因此要将其转换为list,只需将其作为构造函数参数传递。

from itertools import chain

lists = [[1, 2], [3, 4, 5], [6]]
elements = list(chain(*lists))

print(elements)

以上代码打印[1, 2, 3, 4, 5, 6]