2016-11-07 13 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 

該函數返回True如果string可以解釋爲二進制值,如果不是,則爲False

當然,你必須在年底來管理「\ n」的,但你得到的主要思想;)

相關問題