2013-10-27 34 views
1

我有一个由列表理解所产生的列表,并根据调查组这串具有长度为3在stripped它的数据进行排序,我想将它们合并,这样与单个长度字符串分开放置在单个列表中。如何添加列表名单列表中的理解

stripped = ['a,b', 'c,d', 'e', '', 'f,g', 'h', '', ''] 
lst = [[i.split(',')] if len(i) is 3 else i for i in stripped] 
print(lst) 
#[[['a', 'b']], [['c', 'd']], 'e', '', [['f', 'g']], 'h', '', ''] 

我想生产[[['a', 'b'], ['c', 'd'],['f', 'g']], 'e', '','h', '', '']代替

我如何用列表理解,如果可能实现这一目标?

编辑:

接受@HennyH's的答案,因为它的高效率和简单

+0

您需要两个解释。 –

+0

@GamesBrainiac正是我害怕......顺便说一句,我会与移动。如果我*必须* –

+0

@KDawG你也可以简单排序列表 - 看到我的回答。 – user4815162342

回答

4
l = [[]] 
for e in stripped: 
    (l[0] if len(e) == 3 else l).append(e) 
>>> 
[['a,b', 'c,d', 'f,g'], 'e', '', 'h', '', ''] 

或者到OP的为3个长字符串匹配输出:

for e in stripped: 
    l[0].append(e.split(',')) if len(e) == 3 else l.append(e) 
>>> 
[[['a', 'b'], ['c', 'd'], ['f', 'g']], 'e', '', 'h', '', ''] 

这种方式有两个列表A无需额外拼接,作为Inbar的解决方案提供的B。您还可以将stripped转换为生成器表达式,因此您无需在内存中保存两个列表。

+0

我正要发布这个! +1人 –

+0

好但实际上它应该是:'(L [0]如果len(E)== 3否则L).append(e.split( ''))' –

+0

@HennyH但等待即会输出' [['a','b'],['c','d'],['f','g']],['e'],[''],['h'], [“”],[“”]',是不是因为OP希望 –

2

使用两个列表内涵:

>>> stripped = ['a,b', 'c,d', 'e', '', 'f,g', 'h', '', ''] 
>>> first = [x.split(',') for x in (item for item in stripped if len(item) == 3)] 
>>> second = [item for item in stripped if len(item) != 3] 
>>> [first] + second 
[[['a', 'b'], ['c', 'd'], ['f', 'g']], 'e', '', 'h', '', ''] 
2

为什么需要列表理解?最好一次完成。

stripped = ['a,b', 'c,d', 'e', '', 'f,g', 'h', '', ''] 
groups = [] 
final = [groups] 
for item in stripped: 
    if len(item) == 3: 
     groups.append(item.split(',')) 
    else: 
     final.append(item) 

结果:

>>> print(final) 
[[['a', 'b'], ['c', 'd'], ['f', 'g']], 'e', '', 'h', '', ''] 
+0

你甚至可以用'b加= [A]'循环之前,充分满足了单通的要求。 (最后的'[A] + B'在技术上是'B'上的*传球,虽然效率很高。) – user4815162342

+0

@ user4815162342这是真的。 –