2019-10-28 python zip实现条件排序 实现二维list转置

"""
    实现按照学生成绩对学生排序,返回学生名单,成绩高的学生排在前面
"""
students = ['Ben', "Alice", "Sam"]
scores = [99, 19, 23]
res = sorted(zip(students, scores), key=lambda x: x[1], reverse=True)
print("zip的合并效果 ", list(zip(students, scores)))
print("排序的结果    ", list(res))
out = list(zip(*res)) # *的作用是解开list, zip用于重组list
students, scores = out
print(students)


"""
    使用zip实现二维list转置
"""
a = [[1,3,5], [2,4,6]]
print(a)
b = zip(*a) # 这是转置的核心,拆分重组实现转置
print(list(map(list, b)))

程序输出结果:


image.png
总结就是 zip相当于压缩, zip(*)实现解压,可以回到原来的形状
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务