代码之家  ›  专栏  ›  技术社区  ›  mchaudh4

TypeError:ufunc的循环不支持没有可调用sqrt方法的dict类型的参数0

  •  0
  • mchaudh4  · 技术社区  · 5 月前

    我遇到了一个错误:

    psi_out_norm.append(np.sqrt(sorted_probs))
    TypeError: loop of ufunc does not support argument 0 of type dict which has no callable sqrt method
    

    不确定如何解决此错误。下面是我正在编写的代码:

    num_qubits = 2
    sorted_probs = {'00': 0.1826131640519985, '01': 0.3015290853531944, '10': 0.3171301575715357, '11': 0.1987275930232714}
    all_possible_keys = [format(i, f'0{num_qubits}b') for i in range(2**num_qubits)]
    
         
        psi_out_norm = []
        for key in all_possible_keys:  
            count = sorted_probs.get(key, 0) # use 0 is the key is missing
            psi_out_norm.append(np.sqrt(sorted_probs))
    

    如果有人能在这个错误中帮助我,那将是极大的帮助。

    2 回复  |  直到 5 月前
        1
  •  2
  •   Lucenaposition    5 月前

    你正试图逃跑 np.sqrt 在字典上。这就是导致TypeError的原因。您可以替换 sorted_probs 具有 count :

    import numpy as np
    num_qubits = 2
    sorted_probs = {'00': 0.1826131640519985, '01': 0.3015290853531944, '10': 0.3171301575715357, '11': 0.1987275930232714}
    all_possible_keys = [format(i, f'0{num_qubits}b') for i in range(2**num_qubits)]
    
    psi_out_norm = []
    for key in all_possible_keys:  
        count = sorted_probs.get(key, 0) # use 0 is the key is missing
        psi_out_norm.append(np.sqrt(count))
    
        2
  •  1
  •   Matt    5 月前

    np.sqrt()接受一个 array_like 对象。您传入的词典似乎不符合此要求:)

    如果你想得到每个值的平方根 sorted_probs ,你可以这样做:

    import numpy as np
    
    sorted_probs = {'00': 0.1826131640519985, '01': 0.3015290853531944, '10': 0.3171301575715357, '11': 0.1987275930232714}
    psi_out_norm = np.sqrt([prob for _, prob in sorted_probs.items()])
    print(psi_out_norm)
    

    它产生: [0.42733262 0.54911664 0.56314311 0.44578873]