计算每个学生的平均成绩、每门学科的平均成绩
时间: 2024-06-13 11:09:11 浏览: 10
以下是计算每个学生的平均成绩、每门学科的平均成绩的Python代码:
```python
# 假设有3个学生,4门学科
score = [[80, 90, 85, 88], [75, 82, 90, 86], [92, 88, 82, 90]]
# 计算每个学生的平均成绩
stu_avg = []
for i in range(len(score)):
avg = sum(score[i]) / len(score[i])
stu_avg.append(avg)
print("每个学生的平均成绩为:", stu_avg)
# 计算每门学科的平均成绩
sub_avg = []
for i in range(len(score[0])):
sub_score = []
for j in range(len(score)):
sub_score.append(score[j][i])
avg = sum(sub_score) / len(sub_score)
sub_avg.append(avg)
print("每门学科的平均成绩为:", sub_avg)
```
输出结果为:
```
每个学生的平均成绩为: [85.75, 83.25, 88.0]
每门学科的平均成绩为: [82.33333333333333, 86.66666666666667, 85.66666666666667, 88.0]
```
相关问题
利用编程从HBASE中读取学生成绩,并实现计算每个学生成绩平均分和每门课程成绩平均分,用MapReduce方法,使用Java API编程。表中的内容是学号作为行键,姓名和学科作为列族,学科有语文数学英语物理,以及成绩
好的,这里是基于你给出的数据结构,利用Java API编程从HBase中读取学生成绩并实现计算每个学生成绩平均分和每门课程成绩平均分的步骤。
1. 定义HBase的配置信息和表名
```java
Configuration conf = HBaseConfiguration.create();
TableName tableName = TableName.valueOf("student_scores");
```
2. 创建HBase连接和表对象
```java
Connection connection = ConnectionFactory.createConnection(conf);
Table table = connection.getTable(tableName);
```
3. 定义MapReduce作业
```java
Job job = Job.getInstance(conf, "CalculateScores");
job.setJarByClass(CalculateScores.class);
job.setMapperClass(ScoreMapper.class);
job.setReducerClass(ScoreReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(FloatWritable.class);
```
4. 实现Mapper类,读取HBase中的数据,并将每个学生的成绩和课程作为键值对传递给Reducer类
```java
public static class ScoreMapper extends TableMapper<Text, FloatWritable> {
private Text outKey = new Text();
private FloatWritable outValue = new FloatWritable();
public void map(ImmutableBytesWritable row, Result value, Context context) throws IOException, InterruptedException {
String studentId = new String(row.get());
String name = new String(value.getValue(Bytes.toBytes("name"), Bytes.toBytes("name")));
String course = new String(value.getColumnLatestCell(Bytes.toBytes("score"), Bytes.toBytes("course")).getValue());
float score = Float.parseFloat(new String(value.getColumnLatestCell(Bytes.toBytes("score"), Bytes.toBytes(course)).getValue()));
outKey.set(studentId + "," + name + "," + course);
outValue.set(score);
context.write(outKey, outValue);
}
}
```
5. 实现Reducer类,计算每个学生的平均分和每门课程的平均分
```java
public static class ScoreReducer extends Reducer<Text, FloatWritable, Text, FloatWritable> {
private FloatWritable outValue = new FloatWritable();
public void reduce(Text key, Iterable<FloatWritable> values, Context context) throws IOException, InterruptedException {
float sum = 0;
int count = 0;
for (FloatWritable value : values) {
sum += value.get();
count++;
}
float avg = sum / count;
outValue.set(avg);
context.write(key, outValue);
}
}
```
6. 运行MapReduce作业并输出结果
```java
if (job.waitForCompletion(true)) {
Scan scan = new Scan();
ResultScanner scanner = table.getScanner(scan);
float sum = 0;
int count = 0;
float chineseSum = 0;
int chineseCount = 0;
float mathSum = 0;
int mathCount = 0;
float englishSum = 0;
int englishCount = 0;
float physicsSum = 0;
int physicsCount = 0;
for (Result result : scanner) {
String studentId = new String(result.getRow());
String name = new String(result.getValue(Bytes.toBytes("name"), Bytes.toBytes("name")));
String course = new String(result.getColumnLatestCell(Bytes.toBytes("score"), Bytes.toBytes("course")).getValue());
float score = Float.parseFloat(new String(result.getColumnLatestCell(Bytes.toBytes("score"), Bytes.toBytes(course)).getValue()));
sum += score;
count++;
if (course.equals("语文")) {
chineseSum += score;
chineseCount++;
} else if (course.equals("数学")) {
mathSum += score;
mathCount++;
} else if (course.equals("英语")) {
englishSum += score;
englishCount++;
} else if (course.equals("物理")) {
physicsSum += score;
physicsCount++;
}
}
System.out.println("Average score: " + sum / count);
System.out.println("Chinese average score: " + chineseSum / chineseCount);
System.out.println("Math average score: " + mathSum / mathCount);
System.out.println("English average score: " + englishSum / englishCount);
System.out.println("Physics average score: " + physicsSum / physicsCount);
}
```
以上就是利用Java API编程从HBase中读取学生成绩并实现计算每个学生成绩平均分和每门课程成绩平均分的步骤。
Mapreduce求每一科的平均成绩,用数组
好的,这是一个更简单的情况,您可以使用MapReduce来计算每一科的平均成绩,而不需要使用HBase。以下是一些步骤供您参考:
1. 首先,您需要准备好数据。您可以将数据存储在一个文本文件或者一个HDFS文件中。每一行代表一个学生的成绩记录,包括学生ID、学科、成绩等信息,可以使用逗号或者其他分隔符进行分隔。例如:
```
1001,math,80
1002,math,90
1003,math,85
1001,english,70
1002,english,75
1003,english,80
```
2. 接下来,您需要编写一个Mapper类来处理每一行数据。在Mapper类中,您需要将每一行数据转换为键值对的形式,其中键是学科,值是一个包含成绩和计数器的数组。具体来说,您可以使用StringTokenizer类或者正则表达式来解析每一行数据,并将学科作为键,成绩和计数器作为数组中的值。例如:
```java
public class AvgScoreMapper extends Mapper<LongWritable, Text, Text, IntArrayWritable> {
private Text subject = new Text();
private IntArrayWritable scoreArray = new IntArrayWritable();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] fields = value.toString().split(",");
subject.set(fields[1]);
int[] scores = {Integer.parseInt(fields[2]), 1};
scoreArray.set(scores);
context.write(subject, scoreArray);
}
}
```
3. 然后,您需要编写一个Reducer类来计算每一科的平均成绩。在Reducer类中,您需要将接收到的所有值进行合并,并计算每一科的总成绩和学生人数。最后,您可以计算每一科的平均成绩,并将它们作为键值对输出。例如:
```java
public class AvgScoreReducer extends Reducer<Text, IntArrayWritable, Text, DoubleWritable> {
private DoubleWritable avgScore = new DoubleWritable();
public void reduce(Text key, Iterable<IntArrayWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
int count = 0;
for (IntArrayWritable array : values) {
int[] scores = (int[]) array.toArray();
sum += scores[0];
count += scores[1];
}
double avg = (double) sum / count;
avgScore.set(avg);
context.write(key, avgScore);
}
}
```
4. 最后,您需要编写一个Driver类来配置和运行MapReduce作业。在Driver类中,您需要设置输入路径、输出路径、Mapper类、Reducer类等参数,并提交作业到Hadoop集群中运行。例如:
```java
public class AvgScoreDriver {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Average Score");
job.setJarByClass(AvgScoreDriver.class);
job.setMapperClass(AvgScoreMapper.class);
job.setReducerClass(AvgScoreReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntArrayWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
需要注意的是,在本例中,我们使用了一个名为IntArrayWritable的自定义Writable类来保存成绩和计数器的数组。您需要根据自己的需求来决定是否需要使用自定义Writable类。另外,我们也可以使用Combiner类来进一步优化作业性能。