【问题标题】:Multiple column text file to dictionary多列文本文件到字典
【发布时间】:2020-09-10 19:05:39
【问题描述】:

我正在尝试执行以下操作:

我有一个文件可以有任意数量的行和列(意味着输入文件中的行/列数不固定)。另外,请注意可能有重复的点(这是有效的)。 输入文件的格式如下:

Point Sample1_X_Coordinate Sample1_Y_Coordinate Sample2_X_Coordinate Sample2_Y_Coordinate and so on`

A     20                    10                  18                    9

B     16                    13                  15                    13

A     21                    11                  19                    9

C     8                     5                    8                    4

我需要将此文件存储到以下内容中以进行其他操作(添加伪代码,因为我对 python 非常陌生):

outputdata[this_sample][this_point].append((this_sample_point_X_coordinate, this_sample_point_Y_coordinate))

即按以下方式存储的数据:

outputdata[Sample1][A] = list[(20,10), (21,11)]

outputdata[Sample2][A] = list[(18,9), (19,9)]

如何在 python 中实现上述功能?

谢谢!

【问题讨论】:

    标签: python python-3.x python-2.7 dictionary key


    【解决方案1】:

    这可以通过打开文件、逐行读取并用空格分隔行来完成。字典初始化起来很棘手,但使用 defaultdict 对象就相当简单了。例如:

    from collections import defaultdict
    
    # Instantiate a dictionary which assumes dictionary of lists if the key does not exist
    point_dict = defaultdict(lambda: defaultdict(list))
    with open('textfile.txt') as f:
        for line in f.readlines():
            # Split line using space as delimeter and remove new line character:
            point, x1, y1, x2, y2 = line.replace('\n', '').split(' ')
            point_dict['Sample1'][point].append((int(x1), int(y1)))
            point_dict['Sample2'][point].append((int(x2), int(y2)))
    

    这会导致:

    point_dict['Sample1']
    Out[13]: defaultdict(list, {'A': [(20, 10), (21, 11)], 'B': [(16, 13)], 'C': [(8, 5)]})
    
    point_dict['Sample2']
    Out[12]: defaultdict(list, {'A': [(18, 9), (19, 9)], 'B': [(15, 13)], 'C': [(8, 4)]})
    
    point_dict['Sample1']['A']
    Out[14]: [(20, 10), (21, 11)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多