2016-03-03 23 views
-1

电流输入:如何通过两个输入值列组,并将它们设置成一排

reg1 test1 f day1 
reg1 test2 p day1 
reg1 test3 p day2 
reg1 test2 p day2 
reg1 test2 p day3 
reg1 test4 f day3 

所需的输出:

reg test day1 day2 day3 
reg1 test1 f - - 
reg1 test2 p p p 
reg1 test3 - p - 
reg1 test4 - - f 

如何,我可以得到当前输入所需的输出?我只想使用python的内置功能,因为我无法下载类似熊猫,列表等的库。

+0

我认为你正在寻找某种支点?你是否使用任何库进行数据分析,如numpy或类似? – Chris

+1

欢迎来到StackOverflow。请阅读并遵守帮助文档中的发布准则。 [最小,完整,可验证的示例](http://stackoverflow.com/help/mcve)适用于此处。在您发布代码并准确描述问题之前,我们无法有效帮助您。 StackOverflow不是一个编码或教程服务。 – Prune

+0

你到目前为止尝试过什么?你如何得到你的投入?需要更多信息来回答这个问题。 –

回答

0

说你的数据在stuff.csv。通过加载它开始

tups = [l.strip().split(' ') for l in open('stuff.csv') if l.strip()] 
>>> tups 
[['reg1', 'test1', 'f', 'day1'], 
['reg1', 'test2', 'p', 'day1'], 
['reg1', 'test3', 'p', 'day2'], 
['reg1', 'test2', 'p', 'day2'], 
['reg1', 'test2', 'p', 'day3'], 
['reg1', 'test4', 'f', 'day3']] 

现在找到所有可能的天

days = sorted(set(tup[3] for tup in tups)) 
>>> days 
{'day1', 'day2', 'day3'} 

现在计算寄存器和测试

from collections import defaultdict 

d = defaultdict(dict) 
for tup in tups: 
    d[(tup[0], tup[1])][tup[3]] = tup[2] 
>>> d 
defaultdict(dict, 
      {('reg1', 'test1'): {'day1': 'f'}, 
      ('reg1', 'test2'): {'day1': 'p', 'day2': 'p', 'day3': 'p'}, 
      ('reg1', 'test3'): {'day2': 'p'}, 
      ('reg1', 'test4'): {'day3': 'f'}}) 

最后所有条目,计算输出的列表:

out = [] 
for e in d: 
    out.append(
     list(e) + [d[e][day] if day in d[e] else '-' for day in days]) 
>>> out 
[['reg1', 'test2', 'p', 'p', 'p'], 
['reg1', 'test4', '-', 'f', '-'], 
['reg1', 'test1', '-', '-', 'f'], 
['reg1', 'test3', 'p', '-', '-']] 

Outp以CSV格式发送这些内容应该是微不足道的。

0

这似乎是一个简单的加载和卸载嵌套字典的任务。我用sys.stdin例如目的,你的代码很可能来自一个开放的(),所以你可以折腾SYS进口:(改变分割字符匹配您的实际输入)

import sys 

dictionary = {} 

days = set() 

for line in sys.stdin: 
    reg, test, letter, day = line.rstrip().split(' ') 

    if reg not in dictionary: 
     dictionary[reg] = dict() 

    if test not in dictionary[reg]: 
     dictionary[reg][test] = dict() 

    if day not in dictionary[reg][test]: 
     dictionary[reg][test][day] = dict() 

    dictionary[reg][test][day] = letter 

    days.add(day) 

days = sorted(list(days)) 

print("reg", "test#", *days, sep="\t") 

for reg in sorted(dictionary): 
    reg_dict = dictionary[reg] 

    for test in sorted(reg_dict): 
     test_dict = reg_dict[test] 

     letters = [test_dict[day] if day in test_dict else "-" for day in days] 

     print(reg, test, *letters, sep="\t") 

并不完美,但基本上可以工作:

reg  test# day1 day2 day3 
reg1 test1 f  -  - 
reg1 test2 p  p  p 
reg1 test3 -  p  - 
reg1 test4 -  -  f 
相关问题