按值分组和其他分组。

huangapple go评论113阅读模式
英文:

Group by values and other groups

问题

Sure, here is the translated content:

我需要一个算法的帮助。

从表格中

组别
G1 V1
G1 V2
G2 V1
G2 V3
G3 V4
G4 G2
G4 V5

我想要获取组别名称及其值,如果组别包含来自该组的其他组值

G1=V1,V2

G2=V1,V3

G3=V4

G4=V1,V3,V5

我需要用Python编写它,但也可以使用任何语言。

英文:

I need a help with the algorytm.

from the table

Group Value
G1 V1
G1 V2
G2 V1
G2 V3
G3 V4
G4 G2
G4 V5

I would like to get the group names with its values, in case group contains another group values from this group

G1=V1,V2

G2=V1,V3

G3=V4

G4=V1,V3,V5

I need to write it in python but it can be any language

答案1

得分: 1

以下是您提供的Python程序的中文翻译:

# 打开文件
file = open("file.csv", "r")

# 定义一个链接数组类
class link_arr():
    def __init__(self):
        self.linked_groups = []  # 链接的组
        self.values = []  # 值列表

    def __str__(self):
        return str(self.values)

    def __repr__(self):
        return self.__str__()

# 输出字典
output = {}

# 无限循环,直到读取完整个文件
while True:
    line = file.readline()
    if line == '':
        break

    # 分割行并去除空格
    words = line.split(',')
    words = [w.strip() for w in words]

    # 如果输出中没有第一个词,则创建一个新的link_arr对象
    if not words[0] in output:
        output[words[0]] = link_arr()

    # 如果第二个词在输出中,则更新链接的组和值
    if words[1] in output:
        output[words[1]].linked_groups.append(words[0])
        for val in output[words[1]].values:
            output[words[0]].values.append(val)
    else:
        output[words[0]].values.append(words[1])

    # 更新链接组中的值
    for group in output[words[0]].linked_groups:
        output[group].values.append(words[1])

# 打印输出
print(output)

希望这有助于您理解Python程序的功能。

英文:

Here is an example program in python that looks to do what you need!
Edit: I see I've misinterpreted. Will edit again and add group.
program.py

file = open("file.csv", "r")
class link_arr():
    def __init__(self):
        self.linked_groups = []
        self.values = []
    def __str__(self):
        return str(self.values)
    def __repr__(self):
        return self.__str__()

output = {}
while True:
    line = file.readline()
    if line == '':
        break
    words = line.split(',')
    words = [w.strip() for w in words]
    if not words[0] in output:
        output[words[0]] = link_arr()
    if words[1] in output:
        output[words[1]].linked_groups.append(words[0])
        for val in output[words[1]].values:
            output[words[0]].values.append(val)
    else:
        output[words[0]].values.append(words[1])
    for group in output[words[0]].linked_groups:
        output[group].values.append(words[1])
print(output)

file.csv

G1,V1
G1,V2
G2,V1
G2,V3
G3,V4
G4,G2
G4,V5

output:

{'G1': ['V1', 'V2'], 'G2': ['V1', 'V3'], 'G3': ['V4'], 'G4': ['V1', 'V3', 'V5']}

huangapple
  • 本文由 发表于 2023年8月5日 01:24:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定