【问题标题】:Python to print a returned value can be either a list or a int打印返回值的 Python 可以是列表或 int
【发布时间】:2017-12-13 13:42:02
【问题描述】:

我正在使用 pyVCF 读取 VCF 文件,返回的 sample['AD'] 可以是 list,如 [8, 14]int,如 5

如果我使用','.join(map(str,sample['AD'])),它将停在int 返回为“TypeError: 'int' object is not iterable”。

如何编写它以在这两种情况下打印它?


回复评论:

只是普通代码。但是VCF文件自带两种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:

【问题讨论】:

  • 你能改变函数让它总是返回一个列表吗? (所以[5] 现在返回5
  • 您使用的是 pyVCF 中的哪个函数?您可以添加代码的相关部分吗?

标签: python types vcf-variant-call-format


【解决方案1】:

您可以在将输入值初始化为map()时使用if-else

案例一:

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

案例 2:

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

【讨论】:

    【解决方案2】:

    检查结果是列表还是整数的实例

      if instanceof(result,int):
           #print as int
      else:
           #as list
    

    【讨论】:

    • 函数调用isinstance
    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 2017-07-03
    • 1970-01-01
    • 2014-11-16
    • 2015-11-25
    • 1970-01-01
    • 2015-11-21
    • 2019-10-14
    相关资源
    最近更新 更多