首页 > 解决方案 > 使用文件中的数据创建字典值列表

问题描述

我有一种方法可以输入文件夹的路径/目录和文件名。我需要从文件夹中的指定文件名中检索数据并创建一个LIST of DICTIONARIES.

示例文件的一部分如下:

VLSEGEWQLVLHVWAKVEADVAGHGQDILIRLFKSHPETLEKFDRFKHLKTEAEMKASEDLKK

1 137 0 8 7.887

10 127 0 8 7.388

10 130 0 8 5.087

11 131 0 8 5.400

10 134 0 8 4.770

每个文件的第一行应该被忽略。然后,每行中的前两个数字将是分配给键值“pairs”的值,the0和 the8被忽略,最后一个数字是分配给“distance”的值,这是对文件中的每一行执行的,与每一行都是一个新的字典。

所以输出应该看起来像

output = [
   {"pairs": (1,137), "distance": 7.887},

   {"pairs": (10,127), "distance": 7.388},

   {"pairs": (10,130), "distance": 5.087},

   {"pairs": (11,131), "distance": 5.400},

   {"pairs": (10,134), "distance": 4.770},

]

我不确定如何解决这个问题,无论是如何读取文件和文件的每一行。到目前为止,我所拥有的非常基本。我还没有实现创建字典列表。我尝试从基本开始,读取每一行并复制数据,但输出是一个空列表。请注意,这段代码是错误的,而且只是我尝试过的。

def get_rr(self, file_name, path):
    my_lst = []
    #takes every file in folder and put in files list
    for f in os.listdir(path):
        #splits the file name into file name and its extension
        with open(os.path.join(path,f)) as file_object:
                line = file_object.readline()
                while 1:
                    line = file_object.readline().rstrip()
                    if line == "":
                        break
                    my_lst.append(line)

        return my_lst

我的问题:我如何编程以使输出如下所示:

output = [
   {"pairs": (1,137), "distance": 7.887},

   {"pairs": (10,127), "distance": 7.388},

   {"pairs": (10,130), "distance": 5.087},

   {"pairs": (11,131), "distance": 5.400},

   {"pairs": (10,134), "distance": 4.770},

]

标签: pythontuplesreadfile

解决方案


理解非常方便。此外,您可能不需要区分文件路径和名称,操作系统会为您处理。考虑到这一点,这样的事情应该可以工作

def get_ss(self, path):
    with open(path) as file:
        lines = list(file)[2:]
        return [{"pairs":tuple(map(int, words[:2])), "distance":float(words[-1])} for words in (line[:-1].split() for line in lines if line.strip())]

推荐阅读