英文:
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']}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论