2017-11-27 21 views
2

私は文字列のリストを含む大きなリストを作成しようとしています。私は文字列の入力リストを繰り返し、一時的なリストを作成します。 入力:whileループ内でリストのリストをループします

['Mike','Angela','Bill','\n','Robert','Pam','\n',...] 

マイ所望の出力:

[['Mike','Angela','Bill'],['Robert','Pam']...] 

私は何を得る:

[['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...] 

コード:

for i in range(0,len(temp)): 
     temporary = [] 
     while(temp[i] != '\n' and i<len(temp)-1): 
      temporary.append(temp[i]) 
      i+=1 
     bigList.append(temporary) 
+0

https://stackoverflow.com/questions/4322705/split-a-list-into-nested-lists-on-a-valueは、あなたがに見たいかもしれないもののように見えます。 – StardustGogeta

答えて

0

、私は、ネストされたリストに追加する、直接各要素を反復処理をお勧めしたい -

r = [[]] 
for i in temp: 
    if i.strip(): 
     r[-1].append(i) 
    else: 
     r.append([]) 

注意をtempは改行で終わる場合、rは末尾に空を持っていること[]リスト。あなたはそのかかわらを取り除くことができます。

if not r[-1]: 
    del r[-1] 

別のオプションは、他の回答がすでに述べたitertools.groupbyを、使用されるだろう。あなたの方法はより効果的ですが。あなたが試みることができる

3

使用をあなたのコードを修正itertools.groupby

from itertools import groupby 
names = ['Mike','Angela','Bill','\n','Robert','Pam'] 
[list(g) for k,g in groupby(names, lambda x:x=='\n') if not k] 
#[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']] 
0

a_list = ['Mike','Angela','Bill','\n','Robert','Pam','\n'] 

result = [] 

start = 0 
end = 0 

for indx, name in enumerate(a_list):  
    if name == '\n': 
     end = indx 
     sublist = a_list[start:end] 
     if sublist: 
      result.append(sublist) 
     start = indx + 1  

>>> result 
[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']] 
0

あなたのforループは、一時アレイの上にうまくスキャンしましたが、内部のwhileループは、そのインデックスを進めました。そしてあなたのwhileループはインデックスを減らします。これは反逆を引き起こした。

temp = ['mike','angela','bill','\n','robert','pam','\n','liz','anya','\n'] 
# !make sure to include this '\n' at the end of temp! 
bigList = [] 

temporary = [] 
for i in range(0,len(temp)): 
     if(temp[i] != '\n'): 
      temporary.append(temp[i]) 
      print(temporary) 
     else: 
      print(temporary) 
      bigList.append(temporary) 
      temporary = [] 
関連する問題