如何使用嵌套循环从 Python 中的多行中提取列?
How to extract columns from multiple rows in Python using nested loops?
我有一个包含 3 个序列的列表
seq_list = ['ACGT', 'ATTT', 'ACCC']
我想从列表中提取列并使用 python
中的嵌套循环将其存储在另一个列表中
最终输出应该是
seq_list = ['AAA', 'CTC', 'GTC','TTC']
我已经编写了以下代码,但它没有产生所需的输出。
column = []
for i in range(len(seq_list[0])): #Length of the row
for j in range(len(seq_list)): #Length of the column
column.append(seq_list[j][i])
print column
或者,您可以 "zip" the sequence and join:
>>> [''.join(item) for item in zip(*seq_list)]
['AAA', 'CTC', 'GTC', 'TTC']
通过你的方法我做了一点修改,对于每个内部 for
循环我创建了一个 string
然后在内部 for
循环结束后我将它附加到 column
:
seq_list = ['ACGT', 'ATTT', 'ACCC']
column = []
for i in range(len(seq_list[0])): #Length of the row
string = ""
for j in range(len(seq_list)): #Length of the column
string += seq_list[j][i]
column.append(string)
print column
输出:
['AAA', 'CTC', 'GTC', 'TTC']
尽管您可以使用@alecxe 代码(使用zip
和join
)。我认为它很酷而且更像 pythonic。
new_seq_list = reduce(
lambda new_seq_list,item:
new_seq_list + [''.join([item.pop(0) for item in new_seq_list[0]])]
, range(max([len(item) for item in seq_list])) ,
[[list(item) for item in seq_list]]
)[1:]
- 将原始列表转换为字符列表而不是字符串列表
- 为最长字符串中的每个字符减少该列表一次
- 每次减少,将一个字符串添加到新列表中,该字符串由从每个字符列表中删除的第一项组成,并连接在一起。
- 最后,从序列的开头删除现在为空的列表。
我有一个包含 3 个序列的列表
seq_list = ['ACGT', 'ATTT', 'ACCC']
我想从列表中提取列并使用 python
中的嵌套循环将其存储在另一个列表中最终输出应该是
seq_list = ['AAA', 'CTC', 'GTC','TTC']
我已经编写了以下代码,但它没有产生所需的输出。
column = []
for i in range(len(seq_list[0])): #Length of the row
for j in range(len(seq_list)): #Length of the column
column.append(seq_list[j][i])
print column
或者,您可以 "zip" the sequence and join:
>>> [''.join(item) for item in zip(*seq_list)]
['AAA', 'CTC', 'GTC', 'TTC']
通过你的方法我做了一点修改,对于每个内部 for
循环我创建了一个 string
然后在内部 for
循环结束后我将它附加到 column
:
seq_list = ['ACGT', 'ATTT', 'ACCC']
column = []
for i in range(len(seq_list[0])): #Length of the row
string = ""
for j in range(len(seq_list)): #Length of the column
string += seq_list[j][i]
column.append(string)
print column
输出:
['AAA', 'CTC', 'GTC', 'TTC']
尽管您可以使用@alecxe 代码(使用zip
和join
)。我认为它很酷而且更像 pythonic。
new_seq_list = reduce(
lambda new_seq_list,item:
new_seq_list + [''.join([item.pop(0) for item in new_seq_list[0]])]
, range(max([len(item) for item in seq_list])) ,
[[list(item) for item in seq_list]]
)[1:]
- 将原始列表转换为字符列表而不是字符串列表
- 为最长字符串中的每个字符减少该列表一次
- 每次减少,将一个字符串添加到新列表中,该字符串由从每个字符列表中删除的第一项组成,并连接在一起。
- 最后,从序列的开头删除现在为空的列表。