将行更改为列中的文件列表

时间:2017-11-04 23:01:15

标签: python python-3.x

有谁知道如何从此文件中交错分配?

Here is the file, grades.csv and the format.

       Last Name,First Name,Student No.,uTORid,A1,A2,A3,A4
       Smith,Joe,9911991199,smithjoe9,99,88,77,66
       Ash,Wood,9912334456,ashwood,11,22,33,44
       Full,Kare,9913243567,fullkare,78,58,68,88

我希望得到这样的内容然后添加所有作业的总值,然后除以每个作业的作业数量以获得平均值

       [99, 11, 78]
       [88, 22, 58]
       [77, 33, 68]
       [66, 44, 88]

def class_avg(open_file):
'''(file) -> list of float
Return a list of assignment averages for the entire class given the open
class file. The returned list should contain assignment averages in the 
order listed in the given file.  For example, if there are 3 assignments 
per student, the returned list should 3 floats representing the 3 averages.
'''

      new_list = []
for line in open_file:
    grades_list = line.split(',')
    marks1 = grades_list[4:5]
    marks2 = grades_list[6:7]

    for item in range(min(marks1, marks2)):
        added_marks = marks1[item] + marks2[item]

这是我到目前为止所做的,不太确定如何继续

2 个答案:

答案 0 :(得分:0)

在这种情况下,枚举和迭代是你的朋友。使用内置函数

可以很容易地找到平均值
def class_avg(open_file):
    '''(file) -> list of float
    Return a list of assignment averages for the entire class given the open
    class file. The returned list should contain assignment averages in the 
    order listed in the given file.  For example, if there are 3 assignments 
    per student, the returned list should 3 floats representing the 3 averages.
    '''
    marks=[[],[],[],[]]

    for line in open_file:
        grades_list = line.strip().split(',')
        for idx,i in enumerate(range(4,8)):
            marks[idx].append(int(grades_list[i]))    
    avgs = [] 

    for mark in marks:
        avgs.append(float(sum(mark)/(len(mark))))
    return(avgs)

答案 1 :(得分:0)

这样做,昨天我问了一个类似的问题。

void Main()
{
    var counter = BelowValueCounter_UsingFor(46);
    //var counter = BelowValueCounter_UsingLinq(46);
    Console.WriteLine(counter); 
}

decimal[] temperatures = new decimal[] { 40, 40, 45, 60, 70 };

public int BelowValueCounter_UsingLinq(decimal tempValueIn)
{
    return temperatures.Count(a => a < tempValueIn);    
}

public int BelowValueCounter_UsingFor(decimal tempValueIn)
{
    int counter = 0;
    for (int i = 0; i < temperatures.Length; i++)
    {
        if (temperatures[i] < tempValueIn)
            counter++;
    }

    return counter; 
}