[Biopython] Generator expression for SeqIO

Peter Cock p.j.a.cock at googlemail.com
Tue Nov 29 11:15:53 UTC 2011


On Tue, Nov 29, 2011 at 2:06 AM, Mic <mictadlo at gmail.com> wrote:
> Hello,
> How is it possible to use generator expression for the following code?
>
> from Bio import SeqIO
> from Bio.Seq import Seq
> from Bio.SeqRecord import SeqRecord
>
> a = {'a': 'AAA', 1: 'ATC', 3: 'CCT', 2: 'TCT'}
> order = [1, 2, 3, 'a']
> records = (SeqRecord(Seq(seq), id=str(ref), description="") for ref_name in
> order: for ref, seq in a[ref_name].items())
>
> output_handle = open('a.fasta', 'w')
> SeqIO.write(records, output_handle, "fasta")
> output_handle.close()
>
> Error message:
> $ python x.py
>  File "x.py", line 7
>    records = (SeqRecord(Seq(seq), id=str(ref), description="") for
> ref_name in order: for ref, seq in a[ref_name].items())
>
>         ^
> SyntaxError: invalid syntax
>
> Thank you in advance.

Well yes, that is invalid syntax - for a start there is a colon in the middle.

I think you want:

from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
a = {'a': 'AAA', 1: 'ATC', 3: 'CCT', 2: 'TCT'}
order = [1, 2, 3, 'a']
records = (SeqRecord(Seq(a[ref]), id=str(ref), description="") for ref in order)
output_handle = open('a.fasta', 'w')
SeqIO.write(records, output_handle, "fasta")
output_handle.close()

Peter




More information about the Biopython mailing list