-2

我有一个这样的列表:

[[(2L,)], [(3L,)]]

我想转换成这样的列表:

[2, 3]

我怎样才能做到这一点?

4

4 回答 4

5

使用列表推导:

如果元组仅包含一项:

>>> lis = [[(2L,)], [(3L,)]]
>>> [ y[0] for x in lis for y in x]
[2L, 3L]

如果元组包含超过 1 个项目:

>>> [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]
于 2013-06-27T10:09:30.257 回答
0

使用列表推导并将 long 转换为 int:

>>> L = [[(2L,)], [(3L,)]]
>>> result = [int(y[0]) for x in L for y in x]
>>> result
[2, 3]
于 2013-06-27T10:13:32.387 回答
0

要摆脱尾随 L,请使用int()

>>> L = [[(2L,)], [(3L,)]]
>>> [int(i[0][0]) for i in L]
[2, 3]
于 2013-06-27T10:14:38.817 回答
0
>>> d = [[(2L,)], [(3L,)]]
>>> map(lambda x: x[0][0], d)
[2L, 3L]
于 2013-06-27T10:14:49.050 回答