2016-11-07 3 views
1

サンプルは次のようになります。バイナリ要素を持つデータをPythonのリストのリストに解析するには?

lst = ['ms 20 3 -s 10 \n', '17954 11302 58011\n', '\n', '$$\n', 'segsites: 10\n', 'positions: 0.0706 0.2241 0.2575 0.889 \n', '0001000010\n', '0101000010\n', '0101010010\n', '0001000010\n', '\n', '$$\n', 'segsites: 10\n', 'positions: 0.0038 0.1622 0.1972 \n', '0110000110\n', '1001001000\n', '0010000110\n', '$$\n', 'segsites: 10\n', 'positions: 0.0155 0.0779 0.2092 \n', '0000001011\n', '0000001011\n', '0000001011\n'] 

すべての新しいセットが$$で始まります。私はそのようなデータを解析する必要があります、私は以下のリストのリストを持っています。

sample = [['0001000010', '0101000010', '0101010010', '0001000010'],['0110000110', '1001001000', '0010000110'],['0000001011', '0000001011', '0000001011'] # Required Output 

コードは、私がデータを解析し、この権利を取得する方法を把握しようでは初心者です

sample =[[]] 
sample1 = "" 
seqlist = [] 

for line in lst: 
    if line.startswith("$$"): 
     if line in '01': #Line contains only 0's or 1 
      sample1.append(line) #Append each line that with 1 and 0's in a string one after another 
    sample.append(sample1.strip()) #Do this or last line is lost 
print sample 

Output:[[], '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] 

を試みました。説明と一緒にコードを修正する方法に関する提案は高く評価されます。

答えて

1

私は次のようにそれを行うだろう:

基本的に
import re 

lst = ['ms 20 3 -s 10 \n', '17954 11302 58011\n', '\n', '$$\n', 'segsites: 10\n', 'positions: 0.0706 0.2241 0.2575 0.889 \n', '0001000010\n', '0101000010\n', '0101010010\n', '0001000010\n', '\n', '$$\n', 'segsites: 10\n', 'positions: 0.0038 0.1622 0.1972 \n', '0110000110\n', '1001001000\n', '0010000110\n', '$$\n', 'segsites: 10\n', 'positions: 0.0155 0.0779 0.2092 \n', '0000001011\n', '0000001011\n', '0000001011\n'] 

result = [] 
curr_group = [] 
for item in lst: 
    item = item.rstrip() # Remove \n 
    if '$$' in item: 
     if len(curr_group) > 0: # Check to see if binary numbers have been found. 
      result.append(curr_group) 
      curr_group = [] 
    elif re.match('[01]+$', item): # Checks to see if string is binary (0s or 1s). 
     curr_group.append(item) 

result.append(curr_group) # Appends final group due to lack of ending '$$'. 

print(result) 

'$$'が見つかるまで項目を繰り返し処理し、以前に見つかったバイナリ文字を最終結果に追加して、新しいグループを開始します。見つけたすべてのバイナリ文字列(正規表現を使用して)は、現在のグループに追加する必要があります。何'$$'

+0

末尾がないので

は最後に、私は悩み、それはしかし、私の元のデータセットのために働く作りを持っているように見える、進数の最後のセットを追加する必要があります。 https://eval.in/673188 – biogeek

+0

元のデータセットでは、セパレータ($$)が異なります。セパレータのタイプを変更すると、出力が崩壊します。 – biogeek

+0

提案がありますか? – biogeek

1

問題は(少なくとも)ここにあります:if line in '01'です。

この行は、if line == '0' or line == '1'を意味します。これは絶対にあなたが望むものではありません。

基本なく作業アプローチ、それだけ01で構成されている場合、すべての文字列を、テストするであろう:

def is_binary(string) : 
    for c in string : 
     if c not in '01' : 
      return False 
    return True 

stringバイナリとして解釈することができる場合、この関数はTrueを返します値の場合はFalseです。

あなたが最後にその「\ n」を管理する必要がもちろん

ていますが、メインのアイデアを得た;)