[英]Importing data from a dataframe in a txt file into a dictionary
假设以下文本文件
Some lines here
and here
chr1 111 222 More_data_I_dont_need More_data_I_dont_need ...
chr2 333 444 More_data_I_dont_need. More_data_I_dont_need ...
chr3 555 666 More_data_I_dont_need More_data_I_dont_need ...
(数据以 \t 分隔)
我一直在尝试将此数据转换为 Python 字典,其中键存储第一列的值,字典存储第二列和第三列的值。 例如。:
{"chr1": [111, 222], "chr2": [333,444]}
到目前为止我写的代码是:
d = {}
star_end_list = []
with open("file.txt") as f:
for line in f:
if line.startswith('chr'):
chr, start,end = line.split()
star_end_list.append() = start
star_end_list.append() = end
# Then with this data I can create a dictionary. Something like
d[chr] = star_end_list
但我不知道如何忽略第 4、5 等列的值。
您只能检索列表的前 3 项,如下所示。 您的缩进也有一些错误,您使用append
function 的方式,以及您在循环外初始化start_end_list
。 它们也在下面解决。
d = {}
with open("file.txt") as f:
for line in f:
star_end_list = []
if line.startswith('chr'):
chr, start, end = line.split()[:3]
star_end_list.append(start)
star_end_list.append(end)
d[chr] = star_end_list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.