我正在改述我之前的问题,因为输出要求已经改变。
两个列表
fruit_type={apple, apple, orange, orange, pineapple, pineapple, pineapple}
num_type = {2, 1, 1, 2, 3, 1, 2}
预期输出
apple 2
apple 1
orange 1 2
pineapple 3
pineapple 1 2
答案 0 :(得分:0)
proc debugityourself-or-maybe-even-port-to-tcl8.4 {fruit_type num_type} {
foreach fruit $fruit_type num $num_type {
if {[info exists result]&&
([lindex $result end-1 0] eq $fruit)&&
([lindex $result end end] <= $num)} {
lset result end [list {*}[lindex $result end] $num]
} else {
lappend result [list $fruit] [list $num]
}
}
if {[info exists result]} {
return [concat {*}$result]
}
}
UPD:由于需求再次发生变化,这是一个新版本:
proc fruits-of-labour-for-new-requirements {fruit_type num_type} {
foreach fruit $fruit_type num $num_type {
if {[info exists resultF]&&
([lindex $resultF end] eq $fruit)&&
([lindex $resultN end end] <= $num)} {
lset resultN end [list {*}[lindex $resultN end] $num]
} else {
lappend resultF $fruit
lappend resultN [list $num]
}
}
if {[info exists resultF]} {
# $resultF is a list of fruits, $resultN is a list of
# lists with corresponding numbers.
return [list $resultF $resultN]
}
}