簡體   English   中英

如何在具有兩個列表的列表理解中使用枚舉?

[英]How to use enumerate in a list comprehension with two lists?

我剛開始使用列表理解,我正在努力解決它。 在這種情況下,我需要獲取每次迭代的每個列表( sequence_0sequence_1 )的n個數。 我怎樣才能做到這一點?

這個想法是在兩個序列之間獲得最長的相等核苷酸(基序)序列。 一旦找到一對,程序應該在序列的下一個核苷酸中繼續,檢查它們是否也相等,然后用它拉長基序。 最后的 output 應該是找到的所有基序的列表。 問題是,一旦找到一對,要在下一個核苷酸中繼續,我需要兩個序列中的 position 以繼續程序。 index function 在這種情況下不起作用,這就是我需要枚舉的原因。

另外,我不完全理解()之間的xy的原因,理解這一點也很好:)

只是為了解釋一下,列表的內容是 DNA 序列,所以它基本上是這樣的:

sequence_1 = ['A', 'T', 'C', 'A', 'C']
def find_shared_motif(arq):
    data = fastaread(arq)
    seqs = [list(sequence) for sequence in data.values()]
    motifs = [[]]
    i = 0
    sequence_0, sequence_1 = seqs[0], seqs[1]  # just to simplify

    for x, y in [(x, y) for x in zip(sequence_0[::], sequence_0[1::]) for y in zip(sequence_1[::], sequence_1[1::])]:
        print(f'Pairs {"".join(x)} and {"".join(y)} being analyzed...')
        if x == y:
            print(f'Pairs {"".join(x)} and {"".join(y)} match!')
            motifs[i].append(x[0]), motifs[i].append(x[1])
            k = sequence_0.index(x[0]) + 2  # NAO ESTA DEVOLVENDO O NUMERO CERTO
            u = sequence_1.index(y[0]) + 2
            print(k, u)

            # Determines if the rest of the sequence is compatible
            print(f'Starting to elongate the motif {x}...')
            for j, m in enumerate(sequence_1[u::]):
                try:
                    # Checks if the nucleotide is equal for both of the sequences
                    print(f'Analyzing the pair {sequence_0[k + j]}, {m}')
                    if m == sequence_0[k + j]:
                        motifs[i].append(m)
                        print(f'The pair {sequence_0[k + j]}, {m} is equal!')

                    # Stop in the first nonequal residue
                    else:
                        print(f'The pair {sequence_0[k + j]}, {m} is not equal.')
                        break

                except IndexError:
                    print('IndexError, end of the string')

        else:
            i += 1
            motifs.append([])

        return motifs
...

go 的一種方法是開始壓縮兩個列表:

a = ['A', 'T', 'C', 'A', 'C']
b = ['A', 'T', 'C', 'C', 'T']

c = zip(a,b)

在這種情況下, c將具有以下值

c = [('A','A'), ('T','T'), ('C','C'), ('A','C'), ('C','T')]

然后,很明顯,您想要的是將第一個元素與元組與第二個元素進行比較。 但是,您還需要 position 存在差異。 因此,您可以使用enumerate go :

for i, t in enumerate(c):
    if c[0] != c[1]:
        return i
    return -1

這樣,如果最后得到-1 ,則意味着兩個列表中的所有元素都相等,並排。 否則,您將得到 position 的差異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM