【问题标题】:copy items from first list based on a value from second list in Python根据 Python 中第二个列表中的值从第一个列表中复制项目
【发布时间】:2019-11-03 09:12:51
【问题描述】:

我有以下两个列表。

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

我想根据列表 2 中的项目“Joe”从列表 1 中提取项目,然后取提取值的平均值。如何使用循环或列表理解来做到这一点。

例如,从给定学生Joemarks 列表中提取120130130

【问题讨论】:

    标签: python list list-comprehension


    【解决方案1】:

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

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

    如果你只想要一个列表中单个学生的分数,一个简单的理解就是

    [mark for mark, student in zip(marks, students) if student == 'Joe']
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        这可能会有所帮助

        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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-08
          • 1970-01-01
          • 2013-12-06
          • 1970-01-01
          • 2018-09-14
          • 1970-01-01
          • 1970-01-01
          • 2015-10-15
          相关资源
          最近更新 更多