如何根据其他两个列表的排序方式对一个列表进行排序?

2024-10-02 12:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个包含浮点值的列表:

mean_fall_1 = [statistics.mean(d) for d in fall_1_gpa]
stdev_fall_1 = [statistics.stdev(d) for d in fall_1_gpa]

其中:

fall_1_gpa = [[mean(sub_list) for sub_list in list] for list in fall1_grades]

此外,我还有一个字符串列表:

combination_fall_1 = [['CS105','MATH101','ENG101','GER'],['CS105','MATH101','GER','GER']]
fall1_grades = [[[4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0]],[[4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0], [4.0, 3.33, 3.33, 4.0]]]
mean_fall_1 = [2.9687393162393163,3.419960107803423]
stdev_fall_1 = [0.33945301919611576,0.2821718924791329]

我想做的是找到mean_fall_1和stdev_fall_1的最佳组合,并列出它们(首先显示可能的最高平均值和可能的最低stdev,并像这样对它们进行排序)。我所做的是:

mean_fall_1, stdev_fall_1 = sorted(
        list(zip(*(zip(mean_fall_1, stdev_fall_1)))))
    mean_fall_1, stdev_fall_1 = (list(t) for t in sorted(list(zip(*(zip(mean_fall_1, stdev_fall_1))))))

当我打印(stdev,然后是mean)时,我得到以下结果:

[0.2821718924791329, 0.33945301919611576]
[3.419960107803423, 2.9687393162393163]

但是,我希望组合列表能够与此相应地排序,以便我能够向用户显示课程的组合,而不仅仅是平均值和stdev。我试着这样做:

mean_fall_1, stdev_fall_1,combination_fall_1  = sorted(
            list(zip(*(zip(mean_fall_1, stdev_fall_1,combination_fall_1 )))))
        mean_fall_1, stdev_fall_1 = (list(t) for t in sorted(list(zip(*(zip(mean_fall_1, stdev_fall_1,combination_fall_1 ))))))

但我一直在犯这样的错误:

TypeError: '<' not supported between instances of 'list' and 'float'

是否有其他方法根据其他2对组合列表进行排序?还是我遗漏了什么

所需输出:

[['CS105','MATH101','GER','GER'],['CS105','MATH101','ENG101','GER']]

由于{}的平均值为3.419960107803423,其st.dev为0.282178924791329,这是{}与平均值2.9687393162393163和st.dev 0.33945301919611576的更好组合


Tags: in列表forzipmeanlist平均值sorted
1条回答
网友
1楼 · 发布于 2024-10-02 12:28:00

将字符串、mean和stdev压缩在一起,然后问题归结为sorting by one field descending (mean) and another ascending (stdev),同时忽略字符串,然后只需将字符串取出

下面是一个简化的示例:

names = ['a', 'b']
mean = [2.96, 3.41]
stdev = [0.33, 0.28]

groups = list(zip(names, mean, stdev))
groups.sort(key=lambda x: (-x[1], x[2]))
# [('b', 3.41, 0.28), ('a', 2.96, 0.33)]

print([x[0] for x in groups])
# -> ['b', 'a']

相关问题 更多 >

    热门问题