我是TCL的新手,我写了以下代码:
set list1 {{1 2} 3 4}
set list2 {{1 2} 8 1}
if {[lindex $list1 0] == [lindex $list2 0]} { puts "They are equal!"}
但是当我打印子列表元素时,我发现它们是相同的,但 if 语句没有捕获它。为什么?我应该如何正确地进行这种比较?
答案 0 :(得分:6)
我愿意:
# from tcllib
package require struct::list
if {[::struct::list equal $list1 $list2]} { puts "Lists are equal"}
答案 1 :(得分:1)
他们不平等,你正确地测试了。当然你正在打印正确的变量吗?
编辑:我的行为。
# cat test.tcl
set list1 {{1 2} 3 4}
set list2 {{1 2} 8 1}
if {[lindex $list1 0] == [lindex $list2 0]} { puts "They are equal!"}
# tclsh test.tcl
They are equal!
#
答案 2 :(得分:1)
如果我要实施lequal
过程,我会从这开始:
proc lequal {l1 l2} {
foreach elem $l1 {
if {$elem ni $l2} {return false}
}
foreach elem $l2 {
if {$elem ni $l1} {return false}
}
return true
}
然后对此进行优化:
proc K {a b} {return $a}
proc lequal {l1 l2} {
if {[llength $l1] != [llength $l2]} {
return false
}
set l2 [lsort $l2]
foreach elem $l1 {
set idx [lsearch -exact -sorted $l2 $elem]
if {$idx == -1} {
return false
} else {
set l2 [lreplace [K $l2 [unset l2]] $idx $idx]
}
}
return [expr {[llength $l2] == 0}]
}
答案 3 :(得分:1)
#compare two lists with hash table
if {[llength $list1] ne [llength $list2]} {
puts "number of list elements is different"
} else {
puts "there are [llength $list1] list elements"
}
set i 1
foreach a {$list1} b {$list2} {
set a($i) $a
set b($i) $b
incr i
}
for {set j 1} {$j <= [llength $list1]} {incr j} {
if { $a($j) ne $b($j) } {
puts "No Match $a($j) $b($j)"
} else {
puts "Match $a($j) $b($j)"
}
}