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

2024-05-29 11:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要读取sp_list1,这样每个列表中对应位置的三个元素就在一个列表中。接下来的三个(不重叠的)被放入一个单独的列表中,这样一个列表就形成了一个列表。你知道吗

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

期望输出

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

我有一种感觉,这应该是可行的使用类似的列表理解,但我不能弄清楚它(特别是,我不能弄清楚如何访问一个项目的索引,这样一个选择三个连续的索引是不重叠时,使用列表理解)。你知道吗


Tags: 元素列表inputspseqlistttaatg
2条回答
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)

试试这个。我很抱歉,如果它很难理解,不是很精通的文件。你知道吗

你可以在这里使用这个代码,你可以根据你的愿望来操作它。我希望这有帮助:

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']]

相关问题 更多 >

    热门问题