首页 > 解决方案 > 使用阈值操作 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:“列表”和“浮动”实例之间不支持“> =”

我了解此错误的含义,但是我不知道如何解决。

标签: python-3.xlist

解决方案


正如 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

推荐阅读