2016-10-31 33 views
1

我需要閱讀sp_list1,使得來自相應位置的每個列表中的三個元素都在列表中。接下來的三個(不重疊的)被放入一個單獨的列表中,以便列出一個列表。如何使用Python中原始列表中的位置特定元素創建列表列表?

Input: seq_list1 = ['ATGCTATCATTA','ATGCTATCATTA','ATGCTATCATTT'] 

所需的輸出

seq_list_list1 =[['ATG','ATG','ATG'],['CTA','CTA','CTA'],['TCA','TCA','TCA'],['TTA','TTA','TTT']] 

我有一種感覺,這應該使用像列表解析是可行的,但我不能算出它(特別是,我無法弄清楚如何訪問項目的索引,以便在使用列表理解時選擇三個不重疊的連續索引)。

+0

你一定已經意識到'append'需要一個參數。你爲什麼不提供一個? – TigerhawkT3

+0

這是我不確定的一部分。我只是把一個空的列表,就像我編輯過的那樣? – Biotechgeek

+0

它看起來像實際上做你想做的事的代碼與你所嘗試的完全不同(因爲上面給出的原因,它甚至不會沒有錯誤地運行)。這當然是可行的,但SO不是一種編碼服務。你將不得不學習更多,並再次嘗試。 – TigerhawkT3

回答

0

你可以在這裏使用這段代碼,你可以根據你的願望操縱它。我希望它能幫助:

seq_list1 = ['ATGCTATCATTA','ATGCTATCATTA','ATGCTATCATTT'] 
n=3 

seq_list1_empty=[] 
counter = 0 

for k in range(len(seq_list1)+1): 
    for j in seq_list1: 
     seq_list1_empty.append([j[i:i+n] for i in range(0, len(j), n)][counter])# this will reassemble the string as an index 
    counter+=1 

counter1=0 
counter2=3 
final_dic=[] 
for i in range(4): 
    final_dic.append(seq_list1_empty[counter1:counter2])#you access the first index and the third index here 
    counter1+=3 
    counter2+=3 
print final_dic 

輸出是

[['ATG', 'ATG', 'ATG'], ['CTA', 'CTA', 'CTA'], ['TCA', 'TCA', 'TCA'], ['TTA', 'TTA', 'TTT']] 
+0

1)你正在爲他們做某人的工作,而SO不是一個編碼服務。 2)___輸出甚至不正確.___ – TigerhawkT3

+0

我想在這裏幫忙。我仍在檢查輸出PRO:D –

+0

編輯完成後,你仍然在爲他們做零工解釋(對於OP以及未來的訪問者無用),這仍然是錯誤的。 – TigerhawkT3

0
seq_list1 = ['ATGCTATCATTA','ATGCTATCATTA','ATGCTATCATTT'] 


def new_string(string, cut): 
    string_list = list(string) # turn string into list 

    # create new list by appending characters from from index specified by 
    # cut variable 
    new_string_list = [string_list[i] for i in range(cut, len(string_list))] 

    # join list characters into a string again 
    new_string = "".join(new_string_list) 

    # return new string 
    return new_string 


new_sequence = [] # new main sequence 

# first for loop is for getting the 3 sets of numbers 
for i in range(4): 
    sub_seq = [] # contains sub sequence 

    # second for loop ensures all three sets have there sub_sets added to the 
    #sub sequence 
    for set in range(3): 
     new_set = seq_list1[set][0:3] #create new_set 
     sub_seq.append(new_set) # append new_set into sub_sequence 


    #checks if sub_seq has three sub_sets withing it, if so 
    if len(sub_seq) == 3: 
     #the first three sub_sets in seq_list1 sets are removed 
     for i in range(3): 
      # new_string function removes parts of strings and returns a new 
      # string look at function above 

      new_set = new_string(seq_list1[i], 3) # sub_set removed 
      seq_list1[i] = new_set # new set assigned to seq_list1 

    # new_sub sequence is added to new_sequence 
    new_sequence.append(sub_seq) 

    #sub_seq is errased for next sub_sequence 
    sub_seq = [] 


print(new_sequence) 

試試這個。如果難以理解,我很抱歉,文檔不夠精通。

相關問題