如何在Python列表初始化中放入条件

2024-09-28 22:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下清单

poles = [10, 15]
P_D_given_loc_i= np.zeros(40)

然后我会:

P_D_given_loc_i=[(( (i+1) in poles)) for i in range(40) ]

我几乎得到了我想要的。我得到了一个列表,其中在极点之前的所有位置都被标记为True,其余的都是False

事实证明这并不是我想要的。我想得到的是0.0而不是False,1.0而不是True

[ 0.0, 0.0 ,........1.0,  0.0.......]

我的问题是,如何通过在列表初始化中使用if来实现这一点

更广泛的问题是,如何在列表初始化中使用条件句


Tags: in标记falsetrue列表forifnp
1条回答
网友
1楼 · 发布于 2024-09-28 22:25:14

有一种更简单的方法:

poles = np.array([10, 15])
P_D_given_loc_i = np.zeros(40)
P_D_given_loc_i[poles] = 1.0     # Either this,
P_D_given_loc_i[poles + 1] = 1.0 # or this depending on how you define poles.

但是,如果您选择浮动,您最初的方法也会起作用:

P_D_given_loc_i = np.array([float(i+1) in poles for i in range(40)])

但是,对于更大的阵列,这要慢得多

相关问题 更多 >