pythontypesvcf-variant-call-format

Python to print a returned value can be either a list or a int


I am using pyVCF to read a VCF file, and the returned sample['AD'] can either be a list like [8, 14] or an int like 5.

If I use ','.join(map(str,sample['AD'])), it will stop at int returns as "TypeError: 'int' object is not iterable".

How can I write it to print it in both situations?


Reply to the comment:

Just normal code. But the VCF file come with two kinds of AD.

import vcf
vcf_reader = vcf.Reader(filename='xxx.vcf.gz',compressed=True)
for record in vcf_reader.fetch(theChrid):
    for sample in record.samples:

Solution

  • You can use if-else while initializing input value to map()

    Case 1:

    >>> sample['AD'] = [8,14]
    >>> ','.join(map(str, sample['AD'] if isinstance(sample['AD'], list) else list(str(sample['AD']))))
    '8,14'
    

    Case 2 :

    >>> sample['AD'] = 5
    >>> ','.join(map(str, sample['AD'] if isinstance(sample['AD'], list) else list(str(sample['AD']))))
    '5'