返回字符串的Python函数

2024-10-03 17:16:34 发布

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

我使用一个脚本从楼宇自动化系统中检索数据值(没有为此显示脚本),我很想创建一个函数,该函数可以基于数据的摘要统计信息返回字符串。你知道吗

由两部分组成的问题,我只打印如下所示的值,但是否可以返回多个字符串(而不是打印)如果任何条件是真的?你知道吗

下一个问题可能很愚蠢,但是否可以创建一个空列表来编译/附加字符串?如果我能编译大量的数据,我很想玩文本分析。你知道吗

更新了下面的代码

def check_fans(fansData):

    fan_strings = []

    count = fansData.history.count()
    std = fansData.history.std()
    maxy = fansData.history.max()
    mean = fansData.history.mean()
    low = fansData.history.min()


    if std > 5:
        fluxIssue = f'there appears to be fluctuations in the fan speed data like the PID is hunting, std is {std}, {count}'
        fan_strings.append(fluxIssue)
    if mean > 90:
        meanHigh = f'the supply fan speed mean is over 90% like the fan isnt building static, mean value recorded is {mean}, {count}'
        fan_strings.append(meanHigh)
    if mean < 50:
        meanLow = f'the supply fan speed mean is under 50% like there is duct blockage/looks odd, mean value recorded is {mean}, {count}'
        fan_strings.append(meanLow)

    return fan_strings

Tags: the数据字符串ifiscountmeanhistory
2条回答

您完全可以设置一个空字符串并使用for循环来记录数据。尽管我在想象你想做的是循环几组数据并附加某些结果。你知道吗

我不认为将所有这些都插入到函数中是最好的方法。你知道吗

也许你可以把你的功能改成:

def check_fans(fansData):
   count = fansData.history.count()
   std = fansData.history.std()
   maxy = fansData.history.max()
   mean = fansData.history.mean()
   low = fansData.history.min()


results = [] 

fluxIssue = 'there appears to be fluctuations in the fan speed data like the PID is hunting, std is {}, {}'

meanHigh = 'the supply fan speed mean is over 90% like the fan isnt building static, mean value recorded is {}, {}'

meanLow = 'the supply fan speed mean is under 50% like there is duct blockage/looks odd, mean value recorded is {}, {}'

For data in list_of_data:
    check_fans(data)
    if check_fans.std > 5:
        results.append(fluxIssue.format(check_fans.std, check_fans.count))
    if check_fans.mean > 90:
        results.append(meanHigh.format(check_fans.mean, check_fans.count))
    elif check_fans.mean < 50:
        results.append(meanLow.format(check_fans.mean, check_fans.count))
    else:
        continue

print(results)

不过,我还是建议你用字典。你最终会得到一大串数字,我不认为这对任何分析都有很大帮助

is it possible to create like an empty list

当然;[]是一个新创建的空列表,然后您可以像其他任何东西一样给它命名。你知道吗

to compile/append strings?

当然可以;使用常规的列表操作,比如.append。这也解决了原来的问题:

is it possible to return multiple strings (instead of printing) if any of the conditions are TRUE?

建立要返回的字符串列表,然后返回该列表。你知道吗

(顺便说一句,这是一个好主意;一般来说,您希望函数返回有用的数据,而不是直接打印内容—这样,调用代码就可以对该数据执行其他操作,如果有更好的操作,您可以避免打印。)

相关问题 更多 >