首页 > 解决方案 > 从字典调用时的函数输出格式

问题描述

这是我在 python 中使用的函数:

def seqmatchsequence(raw_input):
records = list(SeqIO.parse(raw_input, "fasta"))
d = dict()
for record in records:
    if record.seq in d:
        d[record.seq].append(record)
    else:
        d[record.seq] = [record]
for seq, record_set in d.items():
    if (len(record_set)) != 1:
        print(': (' + str(len(record_set)) + ')')
    for record in record_set:
        if (len(record_set)) != 1:
            print(record.id)

我的输出如下所示:

: (2)
chr1:930227-930591
chr1:948374-948738

我希望它看起来像这样:

: (2)
chr1:930227-930591, chr1:948374-948738

我尝试了我能想到的一切,但我错过了一些东西,有什么建议吗?

标签: pythondictionaryformatting

解决方案


你的函数没有返回任何东西——你只是让它打印字符串到标准输出。

如果您想根据需要返回值,请将这些值串成一个字符串。您现在可以选择打印单个字符串(就像您现在所做的那样):

    for seq, record_set in d.items():
        str_out = None
        if (len(record_set)) != 1:
            str_out = ': (' + str(len(record_set)) + ')')
        for record in record_set:
            if (len(record_set)) != 1:
                str_out += ', ' + record.id
        print(str_out)

或者您可以返回相同的字符串:

    return(str_out)

推荐阅读