python-3.x - 使用阈值操作 Python 列表
问题描述
我需要创建一个函数来比较列表中的每个值,然后相应地设置每个值。代码如下:
actions = [0, 0, 0, 0.5, 0, 0.3, 0.8, 0, 0.00000000156]
def treshold(element, value):
if element >= value:
element == 1
else:
element == 0
treshold(actions, 0.5)
但是,此代码会导致以下错误:
TypeError:“列表”和“浮动”实例之间不支持“> =”
我了解此错误的含义,但是我不知道如何解决。
解决方案
正如 user202729 所指出的那样,一种紧凑的方法是使用列表理解。关键是,您需要对列表中的每个条目执行此操作。如果你想一次在整个列表上运行它,你可以考虑使用 numpy
actions = [0, 0, 0, 0.5, 0, 0.3, 0.8, 0, 0.00000000156]
def treshold(element, value):
thresholded_list = [int(a>=value) for a in actions]
return thresholded_list
这个函数本质上是
def treshold_long(element_list, value):
thresholded_list = []
for element in element_list:
if element >= value:
thresholded_list.append(1)
else:
thresholded_list.append(0)
return thresholded_list
推荐阅读
- arrays - 如何从 Mongoose 的嵌套数组中查找数据?
- azure-durable-functions - 避免在 Orchestrator 功能中多次执行
- python - 通过 python tkinter 运行 shell 脚本
- asp.net-core - net core api newtonsoft.json 检测到类型为“Microsoft.Graph.GraphServiceClient”的属性“客户端”的自引用循环。路径“邀请”
- swift - 表未正确更新
- caching - [Guava 缓存]:确保对 expireAfterAccess/Write 的理解
- tensorflow - OP_REQUIRES 在 decode_wav_op.cc:55 失败:参数无效:只能读取 16 位 WAV 文件,但收到 32
- lda - 词干和词形还原 - 什么方法?
- python - 在 Pandas 中使用另一列作为索引填充一列的最大 n 值 - Python
- amazon-web-services - Amazon SQS 队列是否有指定的 IP 范围或子网?