줄리아 튜플과 사전

이 기사의 목적은 Julia Data Structures Tuple and Dictionary와 이와 관련된 다양한 작업을 이해하는 것입니다.

TUPLES : 쉼표로 구분된 동일하거나 다른 데이터 유형의 고유한 값을 변경할 수 없는 모음입니다.

구문: (항목1, 항목2, 항목3…)

사전: 사전 의 각 값에 해당 키로 액세스할 수 있는 키-값 쌍의 모음입니다. 이러한 키-값 쌍은 동일한 데이터 유형일 필요가 없습니다.

구문: Dict(키1 => 값1, 키2 => 값2, …)

튜플과 메소드()

#create an empty tuple
t1=()
println(“If a Tuple is empty returns “, isempty(t1))
t1=(“julia”,”python”,”sql”)
println(“If a Tuple is non-empty returns “,isempty(t1))
Output:
If a Tuple is empty returns true
If a Tuple is non-empty returns false

#declare a tuple beverage
beverage= (“coffee”,”tea”,”greentea”,”grrencoffee”,”ginger tea”)
#Indexing
println(beverage[1])
Output: coffee
println(beverage[0]) #index in julia starts from 1
BoundsError: attempt to access NTuple{5, String} at index [0]

Stacktrace:
 [1] getindex(t::Tuple, i::Int64)
   @ Base .\tuple.jl:29
 [2] top-level scope
   @ In[7]:2
 [3] eval
   @ .\boot.jl:373 [inlined]
 [4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1196
#Slicing
println(beverage[2:4])
Output:
("tea", "greentea", "grrencoffee")
#Iteration
println("iterating over tuple :")
for i in beverage
    println(i)
end
Output:
iterating over tuple :
coffee
tea
greentea
grrencoffee
ginger tea
#Tuple manipulation:
beverage[3]="chamomile tea"
Output:
MethodError: no method matching setindex!(::NTuple{4, String}, ::String, ::Int64)

Stacktrace:
 [1] top-level scope
   @ In[7]:2
 [2] eval
   @ .\boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1196

튜플 메서드()

#reverse a tuple
rev= reverse(beverage)
println(rev)
Output:("ginger tea", "grrencoffee", "greentea", "tea", "coffee")
#length of tuple
println(“length of tuple “,length(beverage))
Output: length of tuple 5
#check if empty or not
println(isempty(beverage))
Output: false

lang= (l1=”julia”,l2=”python”,l3=”SQL”)
println(lang)
Output: (l1 = "julia", l2 = "python", l3 = "SQL")
println(lang[2])
Output: python
println(lang.l1)
Output: julia

#create a dictionary
empIDs= Dict(“vivek”=>121,”aniket”=>134,”jagdish”=>101)
println(typeof(empIDs))
println(empIDs)
Output:
Dict{String, Int64}
Dict("jagdish" => 101, "vivek" => 121, "aniket" => 134)
#create dict from tuple
eds=[("vivek",2000),("jagdish",5000),("aniket",3500)]
println(typeof(eds))
println(eds)
Output:
Vector{Tuple{String, Int64}}
[("vivek", 2000), ("jagdish", 5000), ("aniket", 3500)]
#conver the tuple into dictionary
edict=Dict(eds)
println(typeof(edict))
println(edict)
Output:
Dict{String, Int64}
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)

println(edict)
Output:
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)
key=keys(edict)
println(“keys are :”,key)
Output: keys are :["jagdish", "vivek", "aniket"]
val=values(edict)
println(“values are :”, val)
Output: values are :[5000, 2000, 3500]
#Iterate over dictionary using for loop 
for (key,val) in edict
    println(key,"=>",val)
end
Output:
jagdish=>5000
vivek=>2000
aniket=>3500

get() 및 getkey()

#get() method: Return the value stored for the given key
#syntax: get(collection, key, default)
println(edict)
Output:
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)
println(get(edict,"vivek",-1))
Output: 2000
#default value is mandatory otherwise it throws error
println("Key not found ",get(edict,"viv",0))
Output: Key not found 0
#wihtout default value
println("Key not found ",get(edict,"viv"))
Output:
MethodError: no method matching get(::Dict{String, Int64}, ::String)
Closest candidates are:
  get(::Dict{K, V}, ::Any, ::Any) where {K, V} at C:\Users\lenovo\AppData\Local\Programs\Julia-1.7.1\share\julia\base\dict.jl:506
  get(::IJulia.IJuliaStdio, ::Any, ::Any) at C:\Users\lenovo\.julia\packages\IJulia\e8kqU\src\stdio.jl:21
  get(::Test.GenericDict, ::Any, ::Any) at C:\Users\lenovo\AppData\Local\Programs\Julia-1.7.1\share\julia\stdlib\v1.7\Test\src\Test.jl:1800
  ...

Stacktrace:
 [1] top-level scope
   @ In[57]:7
 [2] eval
   @ .\boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1196
#getkey()
Return the key matching argument key if one exists in collection, otherwise return default.
println(getkey(edict,"aniket",-1))
Output: aniket
println(getkey(edict,"viv",-1))
Output: -1

println(edict)
Output:
Dict("jagdish" => 5000, "vivek" => 2000, "aniket" => 3500)
delete!(edict,”vivek”)
println(edict)
Output:
Dict("jagdish" => 5000, "aniket" => 3500)
#delete a non-existing item
delete!(edict,"viv")
Output: 
Dict{String, Int64} with 2 entries:
  "jagdish" => 5000
  "aniket"  => 3500

#merge dictionaries using merge()
d1 = Dict(“a”=>1, “b”=>9, “c”=>3)
d2 = Dict(“e”=>7, “f”=>2, “h”=>5)
println(merge(d1,d2))
Output:
Dict("f" => 2, "c" => 3, "e" => 7, "b" => 9, "a" => 1, "h" => 5)
#common keys present
d1 = Dict("a"=>1, "b"=>9, "c"=>3)
d2 = Dict("e"=>7, "b"=>2, "h"=>5)
println(merge(d1,d2))
Output:
Dict("c" => 3, "e" => 7, "b" => 2, "a" => 1, "h" => 5)
#merge dictionaries using mergewith()
d1 = Dict("a"=>1, "b"=>9, "c"=>3)
d2 = Dict("e"=>7, "b"=>2, "h"=>5)
println(mergewith!(+,d1,d2))
Output:
Dict("c" => 3, "e" => 7, "b" => 11, "a" => 1, "h" => 5)

#add new item to a dict
println(edict)
Output: Dict("jagdish" => 5000, "aniket" => 3500)
edict[“vivek”]=2700
println(edict)
Output: Dict("jagdish" => 5000, "vivek" => 2700, "aniket" => 3500)
#change dict vaue for a key
println(edict)
Output: Dict("jagdish" => 5000, "vivek" => 2700, "aniket" => 3500)
edict["vivek"]=4000
println(edict)
Output: Dict("jagdish" => 5000, "vivek" => 4000, "aniket" => 3500)

  • Julia 튜플 및 튜플 방법.
  • 사전 및 방법.

계속 지원하십시오.

Suggested posts

안전한 작업 환경 조성

안전한 작업 환경 조성

“그는 내가 위험에 처했을 때 나를 지켜줄 것입니다. 그가 나를 그의 천막 안에 숨길 것이다.

FY24의 탄소 제거 자금 조달

경로 전반에 걸친 Carbon180의 세출 요청 내역

FY24의 탄소 제거 자금 조달

Alyson Lee, 공무 관리 고문 연방 정부의 연간 예산 책정 과정은 이산화탄소 제거(CDR) 기금 마련을 위한 노력의 핵심입니다. 매년 Carbon180은 내년의 자금 흐름을 안내하기 위해 다양한 의회 사무소에 요청을 제출합니다.

Related posts

지구를 구하고 돈을 버는 방법

지구를 구하고 돈을 버는 방법

페트병, 유리병, 알루미늄캔, 그린에너지 패키지를 무심코 버린 적이 몇 번이나 되셨나요? 재활용에 대한 대가로 무언가를 얻을 수 있기를 몇 번이나 바랐습니까? 당신이 대부분의 사람들과 같다면 대답은 아마도 여러 번일 것입니다. 재활용은 종종 번거로움, 자질구레한 일 또는 즉각적이거나 실질적인 혜택을 가져오지 않는 의무로 간주됩니다.

기독교인에 대한 박해: 우리가 말하지 않는 증오 범죄

이슬람 혐오증은 잊으십시오. 기독교인(및 유대인)은 종교적 증오 범죄의 주요 피해자입니다.

기독교인에 대한 박해: 우리가 말하지 않는 증오 범죄

이성적인 마음을 가진 사람이라면 정치계와 언론계가 좌파, 심지어 극좌파에 의해 지배되고 있다는 사실을 알고 있습니다. 종교 분야에서 이러한 불균형은 분명히 눈에 띕니다. 좌익 신문과 네트워크는 기독교 신앙을 옹호하기 위해 서두르지 않습니다.

작문 실력을 향상시키는 3가지 입증된 방법

글쓰기의 이점과 그렇게 하는 데 도움이 되는 전략

작문 실력을 향상시키는 3가지 입증된 방법

2022년에는 GPT-3가 출시되면서 글쓰기 능력이 덜 중요해진 것 같습니다. AI를 사용하면 글이 서투른 사람들도 양질의 직원을 생성할 수 있습니다.

전화번호만 있으면 누구나 추적 | OSINT 조사

전화번호만 있으면 누구나 추적 | OSINT 조사

OSINT 수사관, CTF 플레이어 또는 단순히 스팸 전화를 받는 사람일 수 있습니다. 광고에서 본 번호를 확인하려는 사람.