根据Python中第二个列表中的值从第一个列表中复制项目

时间:2019-11-03 09:12:51

标签: python list list-comprehension

我有以下两个列表。

marks = [120, 80, 150, 130, 140, 130, 220]
student = ["Joe", "Zoe", "Zoe", "Joe", "Zoe", "Joe", "Zoe"]

我想基于列表2中的项目“ Joe”从列表1中提取项目,然后取提取值的平均值。我该如何使用循环或列表理解功能。

例如,从给定学生120的{​​{1}}列表中提取130130marks

3 个答案:

答案 0 :(得分:1)

您可以将两个列表压缩在一起,并将学生的分数存储在字典中。然后,如果要平均,只需在学生列表中找到学生人数即可。

struct MovieCategoryCell: View {
    var category: String
    var movies:  [MovieBaseProtocol]

    init(category: String, movies: [MovieBaseProtocol]) {
        self.category = category
        self.movies = movies
    }

    var body: some View {
        VStack(alignment: .leading) {
            Text(category)
                .font(.title)
            ScrollView(.horizontal, showsIndicators: false) {
                HStack {
                    ForEach(self.movies, id: \.id) { movie in
                        NavigationLink(destination: MovieUIView(movie: movie)) {
                            MovieCard(movie: movie)
                        }
                    }
                }
            }
            .frame(height: 280)
        }
        .padding(.horizontal, 20)
    }
}

如果您只想要列表中单个学生的分数,那么很容易理解

scores = {}
for mark, student in zip(marks, students):
    scores[student] = scores.get(student, 0) + mark

joe_average = scores['Joe'] / students.count('Joe')

答案 1 :(得分:0)

您可以按以下方式获得该平均值:

joes_marks = [m for m, s in zip(marks, student) if s == 'Joe']
sum(joes_marks) // len(joes_marks)
# 126

答案 2 :(得分:0)

这可能会帮助

from collections import defaultdict

# Create a dict with empty list as default value.
d = defaultdict(list)

# Initialise the list.
student = ["Joe", "Zoe", "Zoe", "Joe", "Zoe", "Joe", "Zoe"]
marks = [120, 80, 150, 130, 140, 130, 220]

# Iterate list with enumerate.
for idx, e in enumerate(student):
    d[e].append(idx)

# Print out the occurrence of 'Joe'. 
res = d['Joe']  

sum_marks=0
for i in res :
    sum_marks += marks[i]

# Prin the output expected
print sum_marks/len(res)