目錄
主要描述一些和數字、數組、字符串 相關操作
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)