我有一个这样的清单:
[[(2L,)], [(3L,)]]
我想转换成如下列表:
[2, 3]
我该怎么做?
答案 0 :(得分:5)
使用列表推导:
如果元组只包含1个项目:
>>> lis = [[(2L,)], [(3L,)]]
>>> [ y[0] for x in lis for y in x]
[2L, 3L]
如果元组包含多个项目:
>>> [z for x in lis for y in x for z in y]
[2L, 3L]
这适用于任何数量的嵌套:
from collections import Iterable
def flatten(collection):
for element in collection:
if isinstance(element, Iterable) and not isinstance(element, basestring):
for x in flatten(element):
yield x
else:
yield element
>>> list(flatten(lis))
[2L, 3L]
>>> lis = [[(2L,)], [(3L,(4,(5,)))]]
>>> list(flatten(lis))
[2L, 3L, 4, 5]
答案 1 :(得分:0)
使用列表推导并将long转换为int:
>>> L = [[(2L,)], [(3L,)]]
>>> result = [int(y[0]) for x in L for y in x]
>>> result
[2, 3]
答案 2 :(得分:0)
要删除尾随的L,请使用int()
:
>>> L = [[(2L,)], [(3L,)]]
>>> [int(i[0][0]) for i in L]
[2, 3]
答案 3 :(得分:0)
>>> d = [[(2L,)], [(3L,)]]
>>> map(lambda x: x[0][0], d)
[2L, 3L]