python - 某些键下的组值

标签 python

到目前为止我的代码:

from collections import OrderedDict as od
    def load(fileIn, fileOut):
        with open(fileIn+'.txt') as fin, open(fileOut+'.txt', 'w') as fout:
            dict = od()
            for line in fin:
                row = line.split()
                id = int(row[0])
                frame = int(row[2])
                rect = [int(row[3]),int(row[4]),int(row[5]),int(row[6])]
                dict = {frame:[id, rect]}
                fout.writelines(str(dict)+'\n')

从文本文件中读取,以特定方式对其进行排序并将其写入新文件。我需要添加另一个 for 循环或可能再添加两个循环,以便我可以在编写它之前更好地对其进行排序,这就是我苦苦挣扎的地方。

以下是输入和输出示例,以使事情更清楚:

输入:

2 109 1 561 1 20 28 1
2 109 2 557 1 24 32 1
2 109 3 557 5 24 32 1
2 109 4 553 5 28 32 1
2 109 5 553 1 36 40 1
239 195 1 101 549 40 28 1
239 195 2 100 549 40 28 1
239 195 3 98 549 40 28 1
239 195 4 91 551 40 28 1
239 195 5 93 549 40 28 1

输出:

 {1: [2, [561, 1, 20, 28]]}
{2: [2, [557, 1, 24, 32]]}
{3: [2, [557, 5, 24, 32]]}
{4: [2, [553, 5, 28, 32]]}
{5: [2, [553, 1, 36, 40]]}
{1: [239, [101, 549, 40, 28]]}
{2: [239, [100, 549, 40, 28]]}
{3: [239, [98, 549, 40, 28]]}
{4: [239, [91, 551, 40, 28]]}
{5: [239, [93, 549, 40, 28]]}

我试图将不同 rect 的所有值分组到一个键下,这是它们共享的公共(public) frame。因此,如果 frame 1 每次在不同的 id 文件中出现 100 次,我需要一个 key 下的所有 rect 其中将包含 100 个不同的 rect

举个例子:

{1:[rect],[rect],[rect],[rect],[rect],[rect],[rect],[rect],[rect]}
{2:[rect],[rect],[rect],[rect],[rect],[rect],[rect],[rect],[rect]}
{3:[rect],[rect],[rect],[rect],[rect],[rect],[rect],[rect],[rect]}

然后我可以将一个文件中的 frame 1 与另一个文件中的 frame 1 进行比较。

最佳答案

这分两步完成,并将中间输出排序为所需的顺序。请注意,每个矩形的 id 都将被忽略,因为它不在您问题中显示的最终输出中。

from collections import defaultdict

def load(fileIn, fileOut):
    with open(fileIn+'.txt') as fin:
        frame_rects = defaultdict(list)

        for row in (map(int, line.split()) for line in fin):
            frame, rect = row[2], [row[3],row[4],row[5],row[6]]
            frame_rects[frame].append(rect)
        fin.close()
        with open(fileOut+'.txt', 'w') as fout:
            for frame, rects in sorted(frame_rects.iteritems()):
                fout.write('{{{}:{}}}\n'.format(frame, rects))

load('filein', 'fileout')

输出:

{1:[[561, 1, 20, 28], [101, 549, 40, 28]]}
{2:[[557, 1, 24, 32], [100, 549, 40, 28]]}
{3:[[557, 5, 24, 32], [98, 549, 40, 28]]}
{4:[[553, 5, 28, 32], [91, 551, 40, 28]]}
{5:[[553, 1, 36, 40], [93, 549, 40, 28]]}

关于python - 某些键下的组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16870998/

相关文章:

python - python中的连接子进程

python - 根据第三个变量中的多个条件,在数据框中为多个子组创建一个新变量

python - 仅从文件中获取新行

python - 无法在 Azure Data Studio 中将内核更改为 Python

python - 使用 selectorgadget.com 解析 HTML 文件

python - 如何在python mysql中防止CREATE查询中的注入(inject)攻击

python - pip 安装不起作用,InvalidSchema : Missing dependencies for SOCKS support

python - Matplotlib 与 Google App Engine

python - 使用过滤器通过 django-polymorphic 限制 GenericForeignKey 模型列表

python - Python游戏程序的抽象和客户端/服务器架构问题