首页 > 解决方案 > 如何在函数定义中使用列表元素作为输入?

问题描述

这是我的代码:

%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' 

标签: pythonlistfunction

解决方案


您将整个列表 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)

推荐阅读