如何在python中压缩列表列表? [英] How to zip a list of lists in python?

查看:87
本文介绍了如何在python中压缩列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表

sample = [['A','T','N','N'],['T', 'C', 'C', 'C']],[['A','T','T','N'],['T', 'T', 'C', 'C']].

我正在尝试压缩文件,以便仅A/T/G/C出现在列表中,并且输出必须是列表

I am trying to zip the file such that only A/T/G/C are in lists and the output needs to be a list

[['AT','TCCC'],['ATT','TTCC']]

当我使用此代码时:

tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in sample]

但是,我只能将输出显示为:

However, I only get the output as:

['ATT','TTCC']

有什么建议可以解决我的问题吗?

Any suggestions where I am going wrong?

在我的实际代码中,我首先转换列表:

In my actual code I am first transposing the lists:

seq_list = [['TCCGGGGGTATC', 'TCCGTGGGTATC', ...]]  # one nested list

numofpops = len(seq_list)

### Tranposing. Moving along the columns only

#column_list = []
for k in range(len(seq_list)):
    column_list = [[] for i in range(len(seq_list[k][0]))]
    for seq in seq_list[k]:
        for i, nuc in enumerate(seq):
            column_list[i].append(nuc)
            ddd = column_list
    print ddd

tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in ddd]
print tt

推荐答案

您的实际代码是丢弃列表.您只能处理最后一个条目.

Your actual code is discarding lists. You only ever process the last entry.

否则,您的代码可以正常工作.只需在循环中执行 ,然后将结果附加到最终列表中即可:

Your code works fine otherwise. Just do that in the loop and then append the result to some final list:

results = []

for k in range(len(seq_list)):
    column_list = [[] for i in range(len(seq_list[k][0]))]
    for seq in seq_list[k]:
        for i, nuc in enumerate(seq):
            column_list[i].append(nuc)
    # process `column_list` here, in the loop (no need to assign to ddd)
    tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in column_list]

    results.append(tt)

请注意,您可以使用zip()函数代替换位列表:

Note that you could use the zip() function instead of your transposition list:

results = []
for sequence in seq_list:
    for column_list in zip(*sequence):
        tt = [''.join([y for y in x if y in 'AGTC']) for x in column_list]
        results.append(tt)

这篇关于如何在python中压缩列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆