python - 如何在函数定义中使用列表元素作为输入?
问题描述
这是我的代码:
%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'
解决方案
您将整个列表 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)
推荐阅读
- java - Spring Boot Data REST 和具有 2 个标识符的资源
- c++ - QML TableView:如何只显示模型索引数据的子集?
- css - 除非我使用检查工具,否则 CSS 不会被覆盖
- java - 如何从 COM-PORT 检索 arudino 传感器数据并将其保存在文本文件中?
- javascript - 在 Angular 中使用来自发布响应的响应数据
- node.js - 无需登录贝宝账户接受信用卡/借记卡付款
- xamarin.android - BufferType.Normal 和 BufferType.Spannable 对 textView 的影响
- java - Android Service queryIntentService 返回空列表
- javascript - NodeJS WebSocket 中的本地持久变量
- python - 如何在 Python 中生成向量