【问题标题】:How do I use the elements of a list as inputs in my function definition?如何在函数定义中使用列表元素作为输入?
【发布时间】:2021-02-03 07:02:18
【问题描述】:

这是我的代码:

%matplotlib inline
import numpy as np
from numpy.random import rand
import matplotlib.pyplot as plt
import random
import math

不同状态的能量值列表

s = [1,-1]
Energy = []
List2 = []



for _ in range(900):
    List = [random.choice(s), random.choice(s), random.choice(s), random.choice(s)]
    E = -(List[0]*List[1]+List[1]*List[2]+List[2]*List[3]+List[3]*List[0])

    List2.append(List)
    Energy.append(E)


Energy = list(dict.fromkeys(Energy))


print(Energy)

1,-1 的所有排列。

a = np.array(List2)


b = np.unique(a, axis=0)
print(b)

分区函数

def Z(E,T,N):
sum = 0
for i in range(0,N):
    sum = sum + math.exp(-E[i]/T)
print(sum)
return sum

Z(Energy,1,3)

概率

for E in Energy:
def p1(E,T,N):
    return math.exp(-E/T)/Z

最后一部分是我挣扎的地方。我正在尝试使用 Energy 的元素作为 概率函数,但我得到了一个错误。

p1(Energy,1,3)

当我运行上面的代码行时,我得到以下错误:

TypeError: bad operand type for unary -: 'list' 

【问题讨论】:

  • 也许你想要[p1(E, 1, 3) for E in Energy]?在循环中定义p1 没有意义;您想在循环中调用它(例如在列表推导中,它将为您提供结果列表)。
  • 类似:def p1(E,T,N): for E in Energy: return math.exp(-E/T)/Z ?
  • 不,就像我说的一样。使用您已经拥有的p1 的定义,但不要在循环中定义它。而是在列表推导中调用它(这是一种循环)。

标签: python list function


【解决方案1】:

您将整个列表 Energy 传递给您的函数,而不是一个元素

改变这个:

 p1(Energy,1,3)

到这里:

p1(E,1,3)

您的完整代码将如下所示:

def p1(E,T,N):
    return math.exp(-E/T)/Z

for E in Energy:
    p1(E,1,3)

【讨论】:

  • 我得到一个 TypeError " unsupported operand type(s) for /: 'float' and 'function' "。我应该输入 E 吗?
  • 在 math.exp(...) 中写这个 Z(E,T,N) 而不是 Z
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 2018-07-25
相关资源
最近更新 更多