2013-10-27 31 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這是真的。 –