如何在列表推导表达式中添加计数器?

时间:2016-02-11 04:33:06

标签: python for-loop

是否可以在下面执行列表推导表达式?

end_pieces = ['ATCGCTGCAATG', 'CCTACGGCATGG', 'AGTACTTTATTA', 'TAACAGTTCTTC']

genome_ht = {'ATCGCTGCAATG': [18], 'CCTACGGCATGG': [30], 'AGTACTTTATTA': [42]}


start_positions = []
count = 0
for read_piece in end_pieces:
    for index in genome_ht[read_piece]:
        start_positions.append(index-(count*KEY_LENGTH))
    count +=1


 >>> print start_positions
 [18, 18, 18]

2 个答案:

答案 0 :(得分:1)

enumerate允许您在没有局部变量的情况下进行计数。除此之外,它是对两个序列的简单嵌套迭代。

end_pieces = ['ATCGCTGCAATG', 'CCTACGGCATGG', 'AGTACTTTATTA', 'TAACAGTTCTTC']
genome_ht = {'ATCGCTGCAATG': [18], 'CCTACGGCATGG': [30], 'AGTACTTTATTA': [42], 'TAACAGTTCTTC': [1]}

KEY_LENGTH = 12
start_positions = [index-count*KEY_LENGTH for count, read_piece in enumerate(end_pieces) for index in genome_ht[read_piece]]

答案 1 :(得分:0)

您可以使用列表理解中的double iteration和函数enumerate执行此操作:

start_positions = [index - count * KEY_LENGTH for count, read_piece in enumerate(end_pieces) for index in genome_ht[read_piece]]