julia - 预先分配一个字典的字典
问题描述
当我在以下函数上运行 @code_warntype 时(以粗体显示的是可能引发危险信号的表达式。)
function cardata(df::DataFrame,Emission_val::Float64,search_cars::Dict{String,Tuple{Int64,Int64}}=Dict("Car1" => (1000,10000), "Car2" => (1000,50000), "Car3" => (1000,6000)),
all_cars::Array{String,1}=["Car1","Car2","Car3","Car4","Car5","Car6"])
**species = Dict()**
# The data file containing car information of interest
car_library = joinpath(path,"cars.csv")
df_car_data=CSV.read(car_library,header=["Model","Velocity","Emission_Value","Mass","Column6"],delim='\t')
#delete unused column
deletecols!(df_car_data, :Column6)
#create a new column with only the car Identifier name
df_car_data[:Identifier_car]=[split(i,r"[0-9]+")[1] for i in df_car_data[:Model]]
#get the properties of all_cars from the cars_data table
for search_models in all_cars
**cars[search_models] = Dict()**
for i in 1:1:length(df_cars_data[1])
num = split(df_cars_data[:Model][i],r"[0-9]+")[1]
alpha = split(df_cars_data[:Model][i],r"[a-zA-Z]+")[2]
if ( num == search_models )
species[num][alpha] = df_car_data[:Velocity][i]
end
end
end
end
我收到以下以红色突出显示的警告:
Body::Tuple{Dict{Any,Any},Union{DataFrame,DataFrameRow{DataFrame,Index}},Any,Any}.
假设我知道将填充字典的数据长度,如何在这种情况下为字典预分配类型?
解决方案
您没有提供最小的工作示例。看看下面的代码。请注意,出于效率原因,建议使用Symbol
密钥而不是String
species = Dict{Symbol,Dict{Symbol,Float64}}()
group = get!(()->Dict{Symbol,Float64}(),species,Symbol("audi"))
group[Symbol("a4")]=10.5
group[Symbol("a6")]=9.5
现在打印输出:
julia> println(species)
Dict(:audi=>Dict(:a6=>9.5,:a4=>10.5))
推荐阅读
- php - 执行 php artisan queue:work on aws elastic beanstalk 无法正常工作
- python - 基于正则表达式连接嵌套字典值
- workflow - 如何在 didag 工作流程中捕获错误时应用 try catch
- python - 不支持的操作数 +
- stripe-payments - 支付宝支付失败,提示“无法识别订单数据...”
- sql - 获取 SQL 列的值并将其用作列名
- apache-kafka - 如何在ksql流中将列分配为KEY
- spartacus-storefront - cx-page-slot 显示在错误的媒体断点中
- azure - 为什么使用的是用户帐户而不是服务主体?
- batch-file - 用于循环文件夹并复制然后重命名的批处理文件