2

Given the following list:

a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]

How to I get:

s = '1.0 1.2 1.4 2.0 2.2 5.0

I can't seem to be able to build something out of join(), map() or list comprehensions that doesn't fail due to the non-iterable last member.

4

3 回答 3

4

这个解决方案有点骇人听闻,但以最小的努力完成了工作

>>> a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]
>>> str(a)
'[[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]'
>>> str(a).translate(None,'[],')
'1.0 1.2 1.4 2.0 2.2 5.0'
于 2013-03-26T16:46:56.903 回答
1
>>> a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]
>>> ' '.join(str(s) for x in a for s in (x if isinstance(x, list) else [x]))
'1.0 1.2 1.4 2.0 2.2 5.0'

这在行为上等同于以下 for 循环:

tmp = []
for x in a:
    if isinstance(x, list):
        for s in x:
            tmp.append(s)
    else:
        tmp.append(x)
result = ' '.join(tmp)

请注意,这假设只有一层嵌套,如您的示例所示。如果您需要它与任意可迭代对象一起工作,而不仅仅是您可以使用的列表collections.Iterable,只要您的值不是字符串(否则它将遍历字符串中的字符)。

于 2013-03-26T16:35:44.820 回答
0

我会去:

a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]

def try_iter(item):
    try:
        return iter(item)
    except:
        return (item,)

from itertools import chain

print ' '.join(str(s) for s in chain.from_iterable(map(try_iter, a)))
于 2013-03-26T16:37:18.627 回答