目录
主要描述一些和数字、数组、字符串 相关操作
1、lpad 填充字符
# lpad(string, n, "p") 打印时,用p的副本在左边填充,使字符串至少有n列宽。
lpad(4,3,"0")
2、使用元编程,转换为String 类型
#使用元编程,转换为String 类型
variablex = 6
typeof(variablex)
#获取参数名称并转为String类型
macro name(arg)
x = string(arg)
quote
$x
end
end
a = @Name(variablex) # 作为一个函数来调用
a = @Name variablex # 作为一个宏标示
#"variablex"
typeof(a)
#将各种数值转为String类型
macro toString(arg)
string(arg)
end
@toString 12
@toString 0.12
3、 生成随机数
#rand() 使用全局的梅森旋转演算法(Mersenne twister)生成器产生伪随机数
#会出现重复的随机数
rand(1:10, 3)
# 3-element Array{Int64,1}:
# 10
# 1
# 1
#使用StatsBase提供的函数就不会出现重复的随机数
using StatsBase
#StatsBase.sample(x,n)函数可以从一列值x中随机有放回抽取n个值。 加replace=false作无放回抽样。 如
MyRand = sample(1:10, 3, replace = false)
# 3-element Array{Int64,1}:
# 3
# 10
# 2
MyRand = sample(1:10, 3, replace = true)
4 判断是否为数字,以及数值转字符串
isa(23, Number)
#true
isa("23", Number)
#false
isa(-1.5, Number)
#true
isa(-1.5, AbstractFloat)
#true
#字符串转数值
parse(Int,"12")
#12
parse(Float16,"1.23")
#1.23
5 随机数组去重,已经统计出现次数
#方法1:使用字典统计出现次数
y=rand(1:10,20)
u=unique(y)
d=Dict([(i,count(x->x==i,y)) for i in u])
println("count for 10 is $(d[10])")
#方法2:StatsBase 中countmap 函数,更好的方法
#返回一个字典,将x中的每个唯一值映射到其出现次数。
using StatsBase
a = countmap(y)
#将字典转为数组
b = hcat([[key, val] for (key, val) in a]...)
6 生成指定范围随机整数 或 随机浮点数 数组
#整数随机数组
x= rand([-1.0,2.0],(3,3))
# 3×3 Array{Float64,2}:
# 2.0 2.0 -1.0
# -1.0 -1.0 2.0
# 2.0 2.0 -1.0
#如果是浮点数,应该是这样
rand(3,3) * (2 - (-1)) .- 1
# 3×3 Array{Float64,2}:
# 1.56676 0.276216 1.98728
# -0.781107 -0.928752 0.952267
# 0.73626 1.4433 -0.693139
#使用Distributions 的 Uniform函数,也可以生成浮点数数组
using Distributions
rand(Uniform(-1,2), 3,3)
7、使用不同大小的Vector 定义一个数组Array
julia> A = [[1,2], [1,2,3], [1,4], [1], [1,5,6,7]]
5-element Array{Array{Int64,1},1}:
[1, 2]
[1, 2, 3]
[1, 4]
[1]
[1, 5, 6, 7]
8、随机字符串
#随机字符串
x = [randstring(3) for _ in 1:10000]
9、排序
x = [randstring(3) for _ in 1:10000]
#不会修改原内容
sort(x)
#会修改原内容
sort!(x)