gpt4 book ai didi

julia - 如何将可能为 `nothing` 的变量插入 Julia 中的字符串中?

转载 作者:行者123 更新时间:2023-12-02 01:29:25 25 4
gpt4 key购买 nike

我试图通过将变量的值插入到字符串中来在 Julia 中创建一个动态字符串。一切正常,直到今天值返回 nothing 给我留下错误。

如何在字符串中包含 nothing?至少不必经历一些 if n == nothing 的麻烦; n = "None" 我想插入到字符串中的每个变量的东西。

function charge_summary(charges_df)
if size(charges_df)[1] > 0
n_charges = size(charges_df)[1]
total_charges = round(abs(sum(charges_df[:amount])), digits=2)
avg_charges = round(abs(mean(charges_df[:amount])), digits=2)
most_frequent_vender = first(sort(by(charges_df, :transaction_description, nrow), :x1, rev=true))[:transaction_description]
sms_text = """You have $n_charges new transactions, totaling \$$total_charges.
Your average expenditure is \$$avg_charges.
Your most frequented vender is $most_frequent_vender.
"""
return sms_text
else
return nothing
end
end

sms_msg = charge_summary(charges_df)


返回:

ArgumentError: `nothing` should not be printed; use `show`, `repr`, or custom output instead.
string at io.jl:156 [inlined]
charge_summary(::DataFrame) at get-summary.jl:18
top-level scope at none:0
include_string(::Module, ::String, ::String, ::Int64) at eval.jl:30
(::getfield(Atom, Symbol("##105#109")){String,Int64,String})() at eval.jl:91
withpath(::getfield(Atom, Symbol("##105#109")){String,Int64,String}, ::String) at utils.jl:30
withpath at eval.jl:46 [inlined]
#104 at eval.jl:90 [inlined]
hideprompt(::getfield(Atom, Symbol("##104#108")){String,Int64,String}) at repl.jl:76
macro expansion at eval.jl:89 [inlined]
(::getfield(Atom, Symbol("##103#107")))(::Dict{String,Any}) at eval.jl:84
handlemsg(::Dict{String,Any}, ::Dict{String,Any}) at comm.jl:168
(::getfield(Atom, Symbol("##14#17")){Array{Any,1}})() at task.jl:259

最佳答案

不幸的是,您必须显式处理nothing。例如像这样:

Your most frequented vender is $(something(most_frequent_vender, "None")).

这样做的原因是不清楚你希望如何将 nothing 转换为字符串,所以你必须提供这个值(在你的情况下你想要 "None ").

一个较短的版本是:

Your most frequented vender is $(repr(most_frequent_vender)).

但是 nothing 被打印为 "nothing"

关于julia - 如何将可能为 `nothing` 的变量插入 Julia 中的字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55200578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com