【问题标题】:adding labels with itertools使用 itertools 添加标签
【发布时间】:2020-11-12 15:16:12
【问题描述】:

我有一个脚本来计算二维矩阵的行列式。 我如何编写每个计算确定的标签? 我创建了一个空列表来填充标签...

这是代码:

import itertools, operator
import numpy as np
list_determinant=[]
list_label=[]
K=[1,2]

l = np.asarray([(100,1),(100,2),(200,5),(200,7)])
print(l)
grouped = itertools.groupby([(label, float(value)) for (label, value) in l], operator.itemgetter(0))

def example(g):
    value = [value for label, value in g]
    xy = np.stack((value,K),axis=1)
    determinant = np.linalg.det(xy) 
    list_determinant.append(determinant)
    return determinant

function = [(label, '%.3f' %round(example(g),3)) for (label, g) in grouped]
print(function)

print(list_determinant)

print(list_label)  #???

【问题讨论】:

    标签: list python-3.6 itertools


    【解决方案1】:

    为什么不从function 列表中提取标签?你的最后几行看起来像:

    ⋮
    
    list_label = [label for (label, _) in function]
    print(list_label)
    

    我会对您的代码进行其他修改,但这只是个人喜好问题:

    import itertools, operator
    import numpy as np
    
    K = (1, 2)
    
    input_values = np.asarray([(100, 1), (100, 2), (200, 5), (200, 7)])
    print(input_values)
    
    values_as_float = ((label, float(value)) for (label, value) in input_values)
    values_grouped = itertools.groupby(values_as_float, operator.itemgetter(0))
    
    def compute_determinants(values_grouped):
        for (current_label, current_group) in values_grouped:
            values = [value for _, value in current_group]
            xy = np.stack((values, K), axis=1)
            determinant = np.linalg.det(xy)
            yield (current_label, determinant)
    
    results = list(compute_determinants(values_grouped))
    results_formatted = [(label, f'{determinant:.3f}') for (label, determinant) in results]
    print(results_formatted)
    
    labels, determinants = list(zip(*results))
    print(determinants)
    print(labels) 
    

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多