-2

随着输出要求的改变,我重新表述了我之前的问题。

两个列表

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
4

1 回答 1

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]
    }
}
于 2013-01-09T22:13:53.280 回答