如何在 Julia 中加入字典,类似于 Python 的一种方式:
diction = {"DC": 4,
"NH": 1,
"MI": 36,
"MO": 4989,
"FL": 157,
"UT": 13,
"NV": 9,
"CA": 110,
"WV": 6,
"NY": 39,
"ME": 1,
"SC": 26,
"KY": 71}
stri = ' | '.join(map(lambda x: '%2.2s %5.5s' % (str(x[0]), str(x[1])), diction.items()))
我想出了什么:
diction = Dict(["DC" => 4
"NH" => 1,
"MI" => 36,
"MO" => 4989,
"FL" => 157,
"UT" => 13,
"NV" => 9,
"CA" => 110,
"WV" => 6,
"NY" => 39,
"ME" => 1,
"SC" => 26,
"KY" => 71])
stri = [@sprintf("%2.2s %5.5s | ",st,ct) for st,ct in keys(diction),values(diction)]
产量:
ERROR: syntax: invalid iteration specification
输出:
DC 4 | NH 1 | MI 36 | MO 4989 | FL 157 | UT 13 | NV 9 | CA 110 | WV 6 | NY 39 | ME 1 | SC 26 | KY 71
在最近的 Julia 版本中,您需要使用“using Printf”引入 sprintf 宏。此外,当迭代字典时,需要将键值对括在括号中
(st, ct)
(Python 不需要;这也适用于枚举 for 循环)。此外,您仍然应该join
在此处使用 a,否则该行将以“|”结尾 分隔器。这然后变成: