如何将文本文件按行的前3个字符分组?

2024-04-20 03:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三张单子列:ID,经度,纬度:


我的文本文件的一部分:

AFJ.SPZ.IR.8    46.84   38.463
AKL.SPZ.IR.11   46.691  38.399
AKL.SPZ.IR.12   46.722  38.407
AFJ.SPZ.IR.3    46.812  38.433
AFJ.SPZ.IR.8    46.84   38.463
AKL.SPZ.IR.11   46.691  38.399
AKL.SPZ.IR.12   46.722  38.407
AKL.SPZ.IR.13   46.654  38.404
AKL.SPZ.IR.25   46.699  38.442
AKL.SPZ.IR.3    46.812  38.433
AKL.SPZ.IR.8    46.84   38.463
ALA.SPZ.IR.3    46.812  38.433
ANAR.BHZ.IR.8   46.84   38.463
ANJ.SPZ.IR.13   46.654  38.404
ANJ.SPZ.IR.18   46.662  38.399
ANJ.SPZ.IR.3    46.812  38.433
BST.SPZ.IR.1    46.732  38.457
BST.SPZ.IR.10   46.707  38.448
BST.SPZ.IR.11   46.691  38.399
BST.SPZ.IR.12   46.722  38.407

我想执行一个函数,以lon和lat的ID有相同的first3字符。 我的代码:

from itertools import groupby

with open('coors1.txt') as fin:
    lines = (line.split() for line in fin)
    for l in lines:
        a=l[0].split(".")
        for key, items in groupby(l,a):
            print (items)

    TypeError: 'str' object is not callable

为什么groupby不理解str?你知道吗


Tags: inidforlineitemssplitlinesgroupby
1条回答
网友
1楼 · 发布于 2024-04-20 03:29:29
  1. 在应用groupby之前,需要对数据进行排序
  2. 您需要将键指定为函数,而不是字符串

    from itertools import groupby
    with open('Input.txt') as fin:
        lines = sorted([line.rstrip() for line in fin])
    for item, grp in groupby(lines, key = lambda x:x.split(".")[0]):
        print item, list(grp)
    

输出

AFJ ['AFJ.SPZ.IR.3    46.812  38.433', 'AFJ.SPZ.IR.8    46.84   38.463', 'AFJ.SPZ.IR.8    46.84   38.463']
AKL ['AKL.SPZ.IR.11   46.691  38.399', 'AKL.SPZ.IR.11   46.691  38.399', 'AKL.SPZ.IR.12   46.722  38.407', 'AKL.SPZ.IR.12   46.722  38.407', 'AKL.SPZ.IR.13   46.654  38.404', 'AKL.SPZ.IR.25   46.699  38.442', 'AKL.SPZ.IR.3    46.812  38.433', 'AKL.SPZ.IR.8    46.84   38.463']
ALA ['ALA.SPZ.IR.3    46.812  38.433']
ANAR ['ANAR.BHZ.IR.8   46.84   38.463']
ANJ ['ANJ.SPZ.IR.13   46.654  38.404', 'ANJ.SPZ.IR.18   46.662  38.399', 'ANJ.SPZ.IR.3    46.812  38.433']
BST ['BST.SPZ.IR.1    46.732  38.457', 'BST.SPZ.IR.10   46.707  38.448', 'BST.SPZ.IR.11   46.691  38.399', 'BST.SPZ.IR.12   46.722  38.407']

相关问题 更多 >