python - 在python中以制表符分隔格式分割文本,将其添加到列表并将其写入文件......有更好的方法吗?

标签 python string list split

我是Python 脚本新手。我正在从制表符分隔的 vcf 文件中提取数据。我的脚本有效,但我尝试使用 word[0:2] 将字符串连接到列表中,但这不起作用,所以我通过手动拆分来添加数据:

即:word[0] + "\t"+ word[1] + "\t"+ word[2]

我不知道为什么我必须这样做,因为当我使用lst = word[0:2]时,命令返回“只能连接列表(而不是“str”)到列表。为什么这是吗?

我的整个代码是:

lst = []
for line in my_file:
    if 'chr' in line:   
        word = line.split("\t")
        adp = word[7].split(";")
        pc = word[9].split(":")
        s = adp[0].split("=")
        lst = word[0] + "\t" + word[1] + "\t" + word[3] + "\t" + word[4] + "\t" + s[1] + "\t" + pc[6] + "\n"
        outputfile.write(lst)

如何使其更简洁?

谢谢

最佳答案

使用join连接字符串时:

lst = []
for line in my_file:
    if 'chr' in line:   
        word = line.split("\t")
        lst.extend(word[7].split(";"))
        lst.extend(word[9].split(":"))
        lst.extend(adp[0].split("="))
        out = '\t'.join(lst)
        outputfile.write(out)

关于python - 在python中以制表符分隔格式分割文本,将其添加到列表并将其写入文件......有更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34061854/

相关文章:

python - Celery/Redis 同一任务并行执行多次

python - Python 脚本中 "for"循环的进度条

Java 11 紧凑字符串 char[] 到 byte[] 背后的魔法

python - python中print语句中第二个括号[]的含义

c - 如何在C中返回列表中的节点

.NET 的 Python : ImportError: No module named warnings

python - 减去数据框中的两个 datetime.time 列

javascript - match() 函数输入的 TypeScript "type"是什么

python 字典列表如何合并键 :value where values are same?

python - 删除 Python 列表中的所有尾随零