简体   繁体   English

将字典值输出到文本文件:解耦列表和字符串

[英]outputting dictionary values to text file: uncoupling lists and strings

I have a dictionary called shared_double_lists which is made of 6 keys called [(0, 1), (1, 2), (1, 3), (2, 3), (0, 3), (0, 2)] .我有一个名为shared_double_lists的字典,它由 6 个键组成,称为[(0, 1), (1, 2), (1, 3), (2, 3), (0, 3), (0, 2)] . The values for all the keys are lists.所有键的值都是列表。

I am trying to output the values for key (0, 1) to a file.我正在尝试将键(0, 1)的值 output 到文件中。 Here is my code:这是我的代码:

output = open('test_output.txt', 'w')
counter = 0
for locus in shared_double_lists[(0, 1)]:
    for value in locus:
        output.write(str(shared_double_lists[(0, 1)][counter]))
        output.write ("\t")
    output.write ("\n")
    counter +=1
output.close()

This almost works, the output looks like this:这几乎可以工作,output 看起来像这样:

['ACmerged_contig_10464', '1259', '.', 'G', 'C', '11.7172', '.', 'DP=1;SGB=-0.379885;MQ0F=0;AC=2;AN=2;DP4=0,0,1,0;MQ=41', 'GT:PL', '1/1:41,3,0']
['ACmerged_contig_10464', '1260', '.', 'A', 'T', '11.7172', '.', 'DP=1;SGB=-0.379885;MQ0F=0;AC=2;AN=2;DP4=0,0,1,0;MQ=41', 'GT:PL', '1/1:41,3,0']

Whereas I want it to look like this:而我希望它看起来像这样:

ACmerged_contig_10464 1259 . G C 11.7172 . DP=1;SGB=-0.379885;MQ0F=0;AC=2;AN=2;DP4=0,0,1,0;MQ=41 GT:PL 1/1:41,3,0
ACmerged_contig_10464 1260 . A T 11.7172 . DP=1;SGB=-0.379885;MQ0F=0;AC=2;AN=2;DP4=0,0,1,0;MQ=41 GT:PL 1/1:41,3,0

ie not have the lines of text in list format in the file, but have each item of each list separated by a tab即文件中没有列表格式的文本行,但每个列表的每个项目都由制表符分隔

You can simply join lists to a string: Docs您可以简单地将列表加入字符串: Docs

my_string = '\t'.join(my_list)

\t should join them with a tab, but you can use what you want there. \t 应该用标签加入它们,但你可以在那里使用你想要的东西。

In this example:在这个例子中:

output.write('\t'.join(shared_double_lists[(0, 1)][counter]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM