【问题标题】:How to take a mode of list of lists, through each list?如何通过每个列表采取列表列表模式?
【发布时间】:2021-11-30 14:58:19
【问题描述】:

我有一个 Python 列表:

a = [[1,2,3], [1,3,3], [0,3,0]]

我想取它的一个模式,这样:

每个列表第零位的模式:1, 1, 0 = 1
每个列表首位的模式:2, 3, 3 = 3
每个列表第二个位置的模式:3, 3, 0 = 3

所以,输出将是:

output = [1, 3, 3]   # expected output

谁能告诉我,如何采取这种模式?

我尝试使用统计库:statistics.mode(a),但它给了我这个错误:TypeError: unhashable type: 'list'。有没有其他方法?

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    使用zip 对列表进行并行迭代:

    from statistics import mode
    
    a = [[1,2,3], [1,3,3], [0,3,0]]
    
    res = [mode(x) for x in zip(*a)]
    print(res)
    

    输出

    [1, 3, 3]
    

    【讨论】:

    • list(map(mode,zip(*a))) :p
    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2015-11-02
    • 2021-12-28
    • 2014-08-05
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多