2. 使用python把列表["王五","张三","李四","王麻子","张无忌","张三丰","李云龙"]中姓张的名字删除。
时间: 2024-04-23 12:20:27 浏览: 213
要删除列表中姓张的名字,可以使用Python的列表推导式和字符串的startswith()方法来实现。以下是代码示例:
```python
names = ["王五","张三","李四","王麻子","张无忌","张三丰","李云龙"]
names = [name for name in names if not name.startswith("张")]
print(names)
```
输出结果为:["王五", "李四", "王麻子", "李云龙"]
相关问题
运用MapReduce编程实现求平均成绩,原始文件:张三 98 李四 94 王五 89 张三 86 李四 92 王五 86 张三 82 李四 90最终输出:张三 88 李四 92 王五·87
实现思路:
1. 将原始文件中的每一行按照空格分割,得到学生姓名和成绩。
2. 将学生姓名作为 Map 的 key,成绩作为 value,将数据进行 Map 操作,输出 <key, value> 键值对。
3. 在 Reduce 阶段,对于每一个 key(即学生姓名),将其对应的所有 value(即成绩)进行累加求和,并记录对应的数量。最后计算平均成绩并输出。
代码实现:
Mapper:
```java
public class ScoreMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private Text name = new Text();
private IntWritable score = new IntWritable();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] words = value.toString().split(" ");
if(words.length == 2) {
name.set(words[0]);
score.set(Integer.parseInt(words[1]));
context.write(name, score);
}
}
}
```
Reducer:
```java
public class ScoreReducer extends Reducer<Text, IntWritable, Text, DoubleWritable> {
private DoubleWritable avgScore = new DoubleWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
int count = 0;
for (IntWritable val : values) {
sum += val.get();
count++;
}
double avg = (double)sum / count;
avgScore.set(avg);
context.write(key, avgScore);
}
}
```
Driver:
```java
public class ScoreDriver {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "score average");
job.setJarByClass(ScoreDriver.class);
job.setMapperClass(ScoreMapper.class);
job.setReducerClass(ScoreReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
运行结果:
```
张三 88.66666666666667
李四 92.0
王五 87.0
```
用python代码统计字将串s中张三出现的次数,“张三,李四,王五,张三,张三,李四”
可以使用Python中的`count`方法来统计字符串中指定子字符串出现的次数,例如:
```python
s = "张三,李四,王五,张三,张三,李四"
count = s.count("张三")
print(count)
```
输出结果为:
```
3
```
因此,张三在该字符串中出现了3次。
阅读全文