如何使用Python中原始列表中的位置特定元素创建列表列表?

时间:2016-10-31 00:26:24

标签: python list position sublist

我需要读取sp_list1,使得来自相应位置的每个列表中的三个元素在列表中。接下来的三个(非重叠)被放入一个单独的列表中,以便列出一个列表。

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

期望输出

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

我觉得这应该是可行的,使用像列表推导这样的东西,但我无法弄清楚(特别是,我无法弄清楚如何访问项目的索引,以便一个选择使用列表推导时不重叠的三个连续索引。)

2 个答案:

答案 0 :(得分: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']]

答案 1 :(得分: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)

试试这个。对不起,如果难以理解,不太精通文档。