我想要一个数组与另一个数组比较的代码/一些提示。如果数组中的一个元素与另一个数组中的元素匹配,则返回 0 并带有 put 语句,否则返回一个带有一些 put 语句的元素。我尝试在互联网上搜索,但找不到任何有用的东西。
array set foodColor {
Apple red
Banana yellow
Lemon yellow
Carrot orange
}
array set citrusColor {
Lemon yellow
Orange orange
Lime green
}
# build up a list of non-citrus foods
foreach k [array names citrusColor] {
if {![info exists foodColor($k)]} {
puts $k;
}
}
在此代码中,输出显示与其他数组中的值不匹配的值。但是我不想要数组中的字符或字符串比较,如果匹配显示输出匹配,我希望与其他数组进行完整的数组比较,否则不匹配。
array set
的语法如下:
array set arrayName list
设置 arrayName 中一个或多个元素的值。 列表必须具有 类似于数组 get 返回的形式,由偶数个 元素。列表中的每个奇数元素都被视为一个元素 数组名称中的名称,列表中的以下元素用作 该数组元素的新值。如果变量数组名称没有 已存在且列表为空,数组名称创建时为空 数组值。
您应该收到以下错误
wrong # args: should be "array set arrayName list"
代码可以重写为,
array set food {
Apple red
Banana yellow
Lemon yellow
Carrot orange
}
array set citrus {
Lemon yellow
Orange orange
Lime green
}
foreach k [array names citrus] {
if {[info exists food($k)]} {
puts "The key '$k' is available in both arrays"
}
}
输出:
The key 'Lemon' is available in both arrays
你想要这个吗?
if { [info exists citrusColor($key)] &&
[info exists foodColor($key)] &&
$citrusColor($key) eq $foodColor($key)
} {
puts "Key $key is in both arrays with the same value"
return 0
} else {
puts "Key $key is either missing or has a different value"
return 1
}